我真的被这个弄糊涂了。在为每个子类管理单独的 HashMap 时遇到一些问题后,我决定尝试使用 instanceof 来简化父类的 HashMap 的操作,该父类将包含任意数量的每个子类。我想出了这个测试代码:
static HashMap <Integer, ant> antMap = new HashMap();
public static void main(String[] args) {
// ant is parent to antF, antSo, and antB
ant testSc = new ant();
antF testF = new antF();
antSo testS = new antSo();
antB testB = new antB();
antMap.put(testSc.ID, testSc);
antMap.put(testF.ID, testF);
antMap.put(testS.ID, testS);
antMap.put(testB.ID, testB);
ant grand = new ant();
int loop = 0;
for (int s = 1; s < 5; s++){
grand = antMap.get(s);
loop++;
if(grand instanceof ant){
System.out.println("type " + grand.type + grand.ID + "Loop " + loop);
}
if(grand instanceof antF){
antF work = (antF) grand;
System.out.println("type " + work.type + work.ID + "Loop " + loop);
}
if(grand instanceof antSo){
System.out.println("type " + grand.type + grand.ID + "Loop " + loop);
}
if(grand instanceof antB){
System.out.println("type " + grand.type + grand.ID + "Loop " + loop);
}
}
我把循环计数器放在那里看看 for 循环是否以某种方式加倍,但输出是:
type Scout1Loop 1
type Forager2Loop 2
type Forager2Loop 2
type Soldier3Loop 3
type Soldier3Loop 3
type Bala4Loop 4
type Bala4Loop 4
我看到父类(此处标记为 scout)正确执行了一次。 ant中的构造函数类根据 Ant 的数量分配一个ID,所以Forager应该是Forager2,Soldier应该是Soldier3等。
我一辈子都弄不明白为什么子类要执行两次。循环计数器显示了这一点。
有人有什么建议吗?
编辑:你可以看到我在 for 循环中尝试了几个不同的东西来获得预期的结果。)
(我确实尝试将其标记为作业,尽管这不是特定的解决方案。)
最佳答案
获得所见输出的一种方法是让 antF
、antSo
和 andB
都扩展类 ant
。在这种情况下,当 grand
是类 antF
的实例时,以下两个 if-s 都将返回 true:grand instanceof ant
和 antF 的宏伟实例
。
解决这个问题的一个简单方法是将最后 3 个 if
-s 更改为 else if
-s,或者将 continue
放入每个 if block 。
关于java - 使用 instanceof 和 HashMap 执行双重命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27559124/