0

I am trying to get a Point2D.Double out of a HashMap for a java game.

 public void Undo(){
    if(Moves.size() >=1)
    {
        GW.ClearBoard();
        Ships.clear();
        Move m =Moves.remove(0);
        HashMap<Ship,Point2D.Double> shipMoves = m.getShips();
        for(Ship s: shipMoves.keySet()){
            if(shipMoves.get(s)!= null){
                Point2D.Double pos = shipMoves.get(s);
                String type = s.getType();
                GW.setShipLocation(pos, type);
                s.setPosition(pos.x, pos.y);
                Ships.add(s);
            }
        }
        System.out.println("Undo");
    }
}

As you can see from the screen captures of me debugging in eclipse, the hash map contains an entry for key=MasterShip(id=87) with a value containing Point2D.Double and the input S is a ship with id=87 and yet the program still returns null and I have no idea why or what I can do about this. I have checked the values in the Move class through the debugger as well.

Correction, there would be images but apparently I cannot post images yet.

edit

You can also iterate over the entrySet() of the map. – Nick Hristov

Thank you, the entryset() method of solving this issue worked perfectly, dunno how to up-vote or set a comment as an answer though.

Duncan Tyrell
  • 150
  • 1
  • 1
  • 11

2 Answers2

1

Iterate over the EntrySet of the Map

   for(Map.Entry<Ship,Point2D.Double> e : shipMoves.entrySet(){
        if(shipMoves.get(s)!= null){
            Point2D.Double pos = e.getValue();
            String type = s.getType();
            GW.setShipLocation(pos, type);
            s.setPosition(pos.x, pos.y);
            Ships.add(s);
        }
    }
Vallabh Patade
  • 4,960
  • 6
  • 31
  • 40
-1

If you use a HashMap with an object as a key, you need to implement two methods:

  1. boolean equals(Object other)
  2. int hashCode()

Check out this question: Creating a hashCode() Method - Java

Community
  • 1
  • 1
Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
  • 2
    It should still work without defining these methods - the same exact object will be `equal()` to itself and have a consistent hash code. What won't work is matching an "equal" key object (one with same field values). – Bohemian Nov 30 '14 at 04:52
  • I am getting the keyset out of the hashmap so it kinda has to be exactly equal to the key does it not? I really don't understand what I have to do to get this to work. – Duncan Tyrell Nov 30 '14 at 04:56