Home > database >  Does HashMap uses hashCode-equals methods of the HashMap or object?
Does HashMap uses hashCode-equals methods of the HashMap or object?

Time:06-08

I am confused regarding to the internal working of HashMap and as far as I understood, HashMap uses hashCode() and equals() methods of the given object that is stored in map (that's why the implementation of these methods are so important). On the other hand, the sources that I followed explains that as if HashMap uses its internal hashCode-equals methods to compare key values. Which one is right? Could you pls clarify me? I know the scenario of put / remove, but just need the place of the hashCode-equals methods. Are they in HashMap or Object?

CodePudding user response:

In HashMap, Keys are hashed and compared, not the values. So, if you want to use your own objects as a Key, you need to implement hashCode and equals methods. e.g. You may want to store Student and corresponding Marksheet in a HashMap then for using Student objects as Key, override hashCode and equals method in that class.
If you just want to use String as key, then HashMap would call hashCode and equals method of String class

CodePudding user response:

It uses it on the Object to facilitate key lookup. Here is an example. Imagine you had 1000 files of individuals in a box and you had the ID number of one you had to find. So you need to go thru the box and search thru 1000 files to find the correct one.

Now imagine that you had two boxes. And all the even id's were in one box marked even and all the odd ones in a box marked odd. By looking at the ID you can pick the proper box (even or odd). So statistically you would only have to search thru about 500 files.

  • So the hashCode generates "boxes" based on the key.
  • And the search for the exact key within a box uses equals.

In my example, hashCode() could return 0 or 1 via something like the following:

@Override
public int hashCode() {
    return id % 2; // returns 0 or 1 for even or odd box
}

Ideally a hashCode that generates many boxes (within reason) is best as the boxes become smaller (holds fewer objects). And a hashCode of a fixed value will work but it reduces the map to a single box with no benefit of improved performance.

  • Related