I have two different sets of HashMap ({u=0, h=3} and {t=3, i=0}), and it is returning the same hashCode (224). I don't understand this, hashCode needs to be different for different objects, and here the HashMap contains different sets of key and value pairs, but it still returns the same hashCode. Can someone please explain how this works?
trying to get the hashcode of the hashmap in java
As Commented, your statement:
is incorrect.
A hash function takes an input, and returns a value derived from the input. The returned value is consistent. The same input always returns the same hash value.
However, two inputs can indeed coincidentally return the same hash value. This is known as a collision. One aspect of a good hash function is that collisions are unlikely. But collisions are always possible. Inputs are infinite but hash values are finite; so obviously collisions must be possible.
Let's test your assertion your two example maps result in the same hash value.
Dump to console.
When run:
Indeed, both your maps result in the same value returned from
hashCode: 224. Our third map results in a different hash value: 177,047,197.If you want to know exactly why those particular inputs result in the same hash value, study the source code from OpenJDK.