Reputation: 7049
When I was trying to get an error from a hashmap with one record I kept getting null. Finally i tested it in the following way:
Iterator<Position> it = pieces.keySet().iterator();
while (it.hasNext()){
System.out.println("object from key >> " + pieces.get(it.next()));
}
Iterator<Piece> itt = pieces.values().iterator();
while (itt.hasNext()){
System.out.println("direct object >> " + itt.next().getPosition());
}
The output I got was:
object from key >> null
direct object >> application.Position@37
The code I have shown was used as it is without anything else in between.
Regarding the position object, I had overridden the hashCode() function to return the hashCode based on the values of the Position class. So when the variables within the object are changed, the HashCode is changed. The above code works well before the position object's value is changed. But once I change the I am getting a null through the key.
Upvotes: 0
Views: 1211
Reputation: 48874
See the relevant documentation for Map
:
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.
A map data structure inspects your object at insertion time in order to determine where it should live (for a HashMap
it inspects the hashCode()
and puts it in a particular bucket, for TreeMap
it compares it against other keys and puts it in a particular branch of the tree, etc.). Maps provide efficient lookup because they then only look where the object is expected to be, and don't search the other buckets / rest of the tree. If you mutate the object after storing it in the map in a way that affects where the map would store it, you break the assumptions the map is making. It will look in the expected bucket, not find it, and give up.
I go into some more detail about the assumptions HashMap
makes and why in this related answer.
Upvotes: 5