My previous OOP experience has been with Objective-C (which is dynamically typed), however, I am now learning Java. I want to iterate over an ArrayList of objects and perform a certain method on them. Every object in the ArrayList is of the same class. In Objective-C, I would just check in each iteration that the object was the correct class, and then run the method, but that technique is not possible in Java:
for (Object apple : apples) {
if (apple.getClass() == Apple.class) {
apple.doSomething(); //Generates error: cannot find symbol
}
}
How do I ‘tell’ the compiler which class the objects in the ArrayList belong to?
In Java 5 and later, collecton types are generified. So you would have this:
It is not generally good practice to have
ArrayLists ofObjectunless you specifically need yourArrayListto be able to hold different types ofObjects. Usually that is not the case, and you can use heterogenous collections for increased type-safety.