Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

On not overriding hashCode() and the usability of the class as a key in a HashMap

 
Steven Squeers
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
In Bates/Sierra there is a question about (inter alia) a class (call it X) that doesn't override hashCode(). Of the possible answers to the question "If instances of class X are to be used as keys in a Map, which are true?", where class X doesn't override hashCode(), this answer is stated as correct:

C. It’s possible for such keys to find the correct entries in the Map.

I thought, you couldn't say this, because
1. Object.hashCode() uses a pseudo memory address. Therefore 2 objects with the same state would have 2 different hashCodes. Also,
2. for any instance o of X, if you put it in a HashMap, serialize it (i.e. o) and deserialize it, won't the hashMap hashCode of the deserialized o be different? Therefore when you try to find it in the HashMap it won't be found?

Is my understanding on either or both of these points wrong?

Thanks in advance.


 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both your points are true in general, almost always. However it's possible that the hashcode will end up the same. Furthermore, it's even more possible that different hashcodes will nonetheless end up in the same bucket in the hashmap (where bucket index is calculated as hashcode % mapsize) which will allow the requested key to be found, even if it doesn't have a properly overridden hashcode. so yes, it's possible the map will work. It is however unlikely that it will work, and failing to override hashCode() in this case is a very bad practice.
 
Steven Squeers
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike, that helps, thanks very much.

SS
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic