-1

The top voted answer of this question states:

When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.

Honestly I don't understand what is the role played by hashCode() with regards to HashSet or HashMap collection objects.

How hashCode() method of key objects is being used in hash-based Collections? Which could be the case where hashCode() of objects change in their lifetime? Can someone elaborate furtherly about this aspect with some example?

3
  • 1
    It's not clear what you question of "Which could be the case where hashCode() of objects change in their lifetime?" is trying to ask, but if you mutate objects such that their hashcodes change after they've been used as keys in a hash table, you won't be able to look those keys up again...
    – Jon Skeet
    Commented Mar 11, 2016 at 16:00
  • 1
    Basically ... it is complicated. You can check out the lastest issues of the Java specialist newsletter ( javaspecialists.eu/archive/Issue235.html ) to get a glimpse of what is required behind the curtains.
    – GhostCat
    Commented Mar 11, 2016 at 16:01
  • 1
    As an example of objects that change their hash in their lifetime have a look at the numerous collections which base their hash on their contents.
    – Thomas
    Commented Mar 11, 2016 at 16:06

1 Answer 1

1

As very clearly stated on this blog post, discussing: How HashMap works in Java

HashMap in Java works on hashing principle. It is a data structure which allows us to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link key and value in HashMap. Objects are stored by calling put(key, value) method of HashMap and retrieved by calling get(key) method. When we call put method, hashcode() method of the key object is called so that hash function of the map can find a bucket location to store value object, which is actually an index of the internal array, known as the table.

Read more: http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html#ixzz42bvBzm6Y

Not the answer you're looking for? Browse other questions tagged or ask your own question.