You need to know the internal representation of the HashMap
.
Actually it is an array of list of key value items, graphically we can represent it as you can see below:
bucket
position
--------
0 NULL
1 --> (K1, V1) --> (K47, V47)
2 NULL
3 NULL
...
54 --> (K89, V89)
...
When you perform a put operation put(key, value) first the code retrieve the hashCode of the key. This value with a module operation is needed to search on the list on the specific bucket.
Then it performs a search element by element on that list performing an equals method to check if the key is already present or not.
If the key is present it replace only the value, if not it will add a new couple key, value at the end of the list.
The pseudo code of the HashMap is similar to the following:
public HashMap {
private List<List<KeyValue<K, V>>> keyValuesBuckets;
public void put(K key, V value) {
int hash = key.hashCode();
int bucketPosition = hash % keyValuesBuckets.size();
for (KeyValue kv : keyValuesBuckets.get(bucketPosition)) {
if (kv.getKey().equals(key)) {
// Key is present change the value and exit
kv.setValue(value);
return;
}
}
// Key is not present
keyValuesBuckets.get(bucketPosition).add(new KeyValue(key, value));
}
Note that the code is not the real code. There is no check on the null values for example, but it gives you the idea on how the equality is checked using both hashCode and equals methods.
To have a more in depth details on how it works start from the definition of [hashCode
][1]:
Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.
and [equals
][2]
In the javadoc you can find the contract that equals
and hashCode
must supply so that a class can be used as a key in a HashMap
:
The general contract of hashCode is:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
[1]: https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--
[2]: https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-