As per my understanding I think:
- It is perfectly legal for two objects to have the same hashcode.
- If two objects are equal (using the equals() method) then they have the same hashcode.
- If two objects are not equal then they cannot have the same hashcode
Am I correct?
Now if am correct, I have the following question:
The HashMap
internally uses the hashcode of the object. So if two objects can have the same hashcode, then how can the HashMap
track which key it uses?
Can someone explain how the HashMap
internally uses the hashcode of the object?
I will not get into the details of how HashMap works, but will give an example so we can remember how HashMap works by relating it to reality.
We have Key, Value ,HashCode and bucket.
For sometime, we will relate each of them with the following:
Using Map.get(key) :
Stevie wants to get to his friend's(Josse) house who lives in a villa in a VIP society, let it be JavaLovers Society. Josse's address is his SSN(which is different for everyone). There's an index maintained in which we find out the Society's name based on SSN. This index can be considered to be an algorithm to find out the HashCode.
Using Map.put(key,Value)
This finds a suitable society for this Value by finding the HashCode and then the value is stored.
I hope this helps and this is open for modifications.
HashMap
is an array ofEntry
objects.Consider
HashMap
as just an array of objects.Have a look at what this
Object
is:Each
Entry
object represents a key-value pair. The fieldnext
refers to anotherEntry
object if a bucket has more than oneEntry
.Sometimes it might happen that hash codes for 2 different objects are the same. In this case, two objects will be saved in one bucket and will be presented as a linked list. The entry point is the more recently added object. This object refers to another object with the
next
field and so on. The last entry refers tonull
.When you create a
HashMap
with the default constructorThe array is created with size 16 and default 0.75 load balance.
Adding a new key-value pair
hash % (arrayLength-1)
where element should be placed (bucket number)HashMap
, then value gets overwritten.If the bucket already has at least one element, a new one gets added and placed in the first position of the bucket. Its
next
field refers to the old element.Deletion
hash % (arrayLength-1)
Entry
. If a desired element is not found, returnnull