gpt4 book ai didi

java - 计算每种类型的对象数量 - Instanceof 或 getClassName

转载 作者:行者123 更新时间:2023-12-01 07:01:11 25 4
gpt4 key购买 nike

我有三个类(class) - One , Two extends One , Three extends Two

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

ArrayList<One> v = new ArrayList<>(3);
v.add(new One();
v.add(new Two();
v.add(new Three();

工作代码:

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);

}

不工作的代码 - 使用 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);

}

为什么我的代码不能与 instanceof 一起使用?它不是应该获取“正确”类型的对象吗?

谢谢。

最佳答案

因为任何 TwoThree 也是 One,因此所有内容都符合第一个条件。

首先检查Three;然后检查 Two;然后一个最后。

关于java - 计算每种类型的对象数量 - Instanceof 或 getClassName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49696433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com