计算每个类型的对象数 - Instanceof或getClassName

Ass*_*saf 0 java instanceof

我有三个类- ,,OneTwo extends OneThree extends Two

我必须编写一个方法来计算每个类中存在多少个实例ArrayList<One>.

ArrayList<One> v = new ArrayList<>(3);
    v.add(new One();
    v.add(new Two();
    v.add(new Three();
Run Code Online (Sandbox Code Playgroud)

工作代码:

public static void test2(ArrayList<One> v){
    String className = "";
    int countOne = 0, countTwo = 0, countThree = 0;
    for (int i = 0; i <v.size() ; i++) {
        className = v.get(i).getClass().getSimpleName();
        if (className.equals("One")){
            countOne++;
        }
        else if (className.equals("Two")){
            countTwo++;
        }
        else{
            countThree++;
        }

    }
    System.out.println("One = "+countOne + "Two = " + countTwo + "Three = " +countThree);

}
Run Code Online (Sandbox Code Playgroud)

不工作的代码 - 与Instanceof

public static void test2(ArrayList<One> v){
    String className = "";
    int countOne = 0, countTwo = 0, countThree = 0;
    for (int i = 0; i <v.size() ; i++) {
        if (v.get(i) instanceof One){
            countOne++;
        }
        else if (v.get(i) instanceof Two){
            countTwo++;
        }
        else{
            countThree++;
        }

    }
    System.out.println("One = "+countOne + "Two = " + countTwo + "Three = " +countThree);

}
Run Code Online (Sandbox Code Playgroud)

为什么我的代码不适用instanceof?是不是应该获取对象的"正确"类型?

谢谢.

And*_*ner 8

因为任何a Two或a Three也是a One,所以一切都符合第一个条件.

Three先检查一下; 然后检查Two; 然后One持续.