转换对象的类

MJe*_*yes 3 java

我以前的OOP经验是使用Objective-C(动态类型),但是,我现在正在学习Java.我想迭代对象的ArrayList并对它们执行某种方法.ArrayList中的每个对象都属于同一个类.在Objective-C中,我只是在每次迭代中检查对象是否是正确的类,然后运行该方法,但在Java中这种技术是不可能的:

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

如何"告诉"编译器ArrayList中的对象属于哪个类?

dan*_*ben 10

在Java 5及更高版本中,收集器类型是通用的.所以你会有这个:

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

for (Apple apple : a) {
    apple.doSomething();
}
Run Code Online (Sandbox Code Playgroud)

除非你特别需要你能够拥有不同类型ArrayList的东西,Object否则通常不是很好的做法.通常情况并非如此,您可以使用异类集合来提高类型安全性.ArrayListObjects


akf*_*akf 5

对于传统铸造,请考虑:

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

在Java的更高版本中,引入了泛型,无需进行这些类型的测试.