我有三个类- ,,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?是不是应该获取对象的"正确"类型?
谢谢.
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |