开发者

Casting an object's class

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 bel开发者_如何学Cong to?


In Java 5 and later, collecton types are generified. So you would have this:

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

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

It is not generally good practice to have ArrayLists of Object unless you specifically need your ArrayList to be able to hold different types of Objects. Usually that is not the case, and you can use heterogenous collections for increased type-safety.


for traditional casting, consider this:

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

in later versions of Java, Generics were introduced that obviate the need for these sorts of tests.


Reading the section on casting from the Java Tutorial should answer that question.

(Or, if you declare the ArrayList yourself, use an approapriate type parameter as danben suggests=


You need to cast Object apple to Apple.

((Apple)apple).doSomething();

But in this specific case, it's better to use;

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜