计算每种类型的对象数量 - Instanceof 或 getClassName
Counting Number of Object from each Type - Instanceof or getClassName
我有三个 classes - One
, Two extends One
, Three extends Two
我必须编写一个方法来计算 ArrayList<One>
中每个 class 的实例数量。
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
?它不是应该获取对象的 "right" 类型吗?
谢谢。
因为任何 Two
或 Three
也是 One
,所以一切都符合第一个条件。
首先检查 Three
;然后检查 Two
;然后 One
最后。
我有三个 classes - One
, Two extends One
, Three extends Two
我必须编写一个方法来计算 ArrayList<One>
中每个 class 的实例数量。
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
?它不是应该获取对象的 "right" 类型吗?
谢谢。
因为任何 Two
或 Three
也是 One
,所以一切都符合第一个条件。
首先检查 Three
;然后检查 Two
;然后 One
最后。