Feature class casting

My previous OOP experience was with Objective-C (which is dynamically typed), however now I am learning Java. I want to iterate over ArrayList objects and execute a specific method on them. Each object in an ArrayList has one class. In Objective-C, I would simply check at each iteration that the object was the correct class, and then run the method, but this technology is not possible in Java:

for (Object apple : apples) {
        if (apple.getClass() == Apple.class) {
            apple.doSomething(); //Generates error: cannot find symbol
        }
    }

How do I say "compiler, to which class do the objects in ArrayList belong?

+3
source share
4 answers

In Java 5 and later, collection types are generated. So you will have the following:

ArrayList<Apple> a = getAppleList(); // list initializer

for (Apple apple : a) {
    apple.doSomething();
}

ArrayList Object, ArrayList Objects. , .

+10

, :

for (Object apple : apples) {
    if (apple instanceof Apple) { //performs the test you are approximating
        ((Apple)apple).doSomething(); //does the cast
    }
}

Java, Generics, .

+5

Java .

(, ArrayList, Approapriate, danben =

+1

Object apple Apple.

((Apple)apple).doSomething();

;

for(Apple apple : apples){
    apple.doSomething();
}
0

Source: https://habr.com/ru/post/1731298/


All Articles