Double command execution with instanceof and HashMap <p>I'm really flummoxed by this one. After having some problems managing separate HashMaps for each child class, I decided to try using instanceof to make things simpler with a HashMap of the Parent class that will include any number of each of the child classes. I came up with this test code:</p> <pre><code>static HashMap &lt;Integer, ant&gt; 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 &lt; 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); } } </code></pre> <p>I put the loop counter in there to see if the for loop was doubling up somehow but the output is: </p> <pre><code>type Scout1Loop 1 type Forager2Loop 2 type Forager2Loop 2 type Soldier3Loop 3 type Soldier3Loop 3 type Bala4Loop 4 type Bala4Loop 4 </code></pre> <p>I see the parent class (labeled scout here) executes once correctly. The constructor class in ant assigns an ID based on the number of ants, so the Forager should be Forager2, Soldier should be Soldier3, etc.</p> <p>I cannot for the life of me figure out why the child classes are executing twice. The loop counter shows this. </p> <p>Does anyone have any suggestions?</p> <p>Edit: you can see I tried a couple different things within the for loop to get the expected results.)</p> <p>(I did try to tag this as homework, although this is not a specific solution.)</p>