Videos
You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:
String[] elements = {"a", "a", "a", "a"};
for (String s: elements) {
//Do your stuff here
System.out.println(s);
}
String[] elements = { "a", "a", "a", "a" };
for( int i = 0; i < elements.length - 1; i++)
{
String element = elements[i];
String nextElement = elements[i+1];
}
Note that in this case, elements.length is 4, so you want to iterate from [0,2] to get elements 0,1, 1,2 and 2,3.
Found the answer
public class App {
public static void main(String[] args) throws Exception {
Car car = new Car();
Bicycle bicycle = new Bicycle();
Van van = new Van();
Object[] racers = {car, bicycle, van};
for(Object x : racers) {
System.out.println(x.getClass());
((Vehicle) x).go(); // this is the only change I made
}
}
}
The following would have worked
Vehicle[] racers = {car, bicycle, van};
for (Vehicle x : racers) { ... x.go();
Dynamic detection does works too. You could use the modern Stream<?>.
Object[] racers = {car, bicycle, van};
Arrays.stream(racers)
.filter(r -> r instanceOf(Vehicle)
.map(Vehicle.class::cast)
.forEach(r -> {
r.go(); ...
};
Since atleast Java 1.5.0 (Java 5) the code can be cleaned up a bit. Arrays and anything that implements Iterator (e.g. Collections) can be looped as such:
public static boolean inArray(int[] array, int check) {
for (int o : array){
if (o == check) {
return true;
}
}
return false;
}
In Java 8 you can also do something like:
// import java.util.stream.IntStream;
public static boolean inArray(int[] array, int check) {
return IntStream.of(array).anyMatch(val -> val == check);
}
Although converting to a stream for this is probably overkill.
You should definitely encapsulate this logic into a method.
There is no benefit to repeating identical code multiple times.
Also, if you place the logic in a method and it changes, you only need to modify your code in one place.
Whether or not you want to use a 3rd party library is an entirely different decision.