Working of HashMap Get Method

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

In previous article, we’ve learned how HashMap put method works with the help of hashcode of the object that is being put as key. This article will explain the working of hashmap get method.

 

Working of HashMap Get Method:

We will continue with the same example that we saw in hashmap put method example (Please read this before going further).  We have a class Bike as below.

Bike.java:

and we’ve added three bikes into bikes map as below.

After this, bikes map is represented by below diagram.

complete hashmap

 

Point to note here is that cbr250r and ninja250r have same hashcode and hence they fall in same bucket. Now let us say we call hashmap get method on ninja250r as below.

Here is how HashMap get method works in this case. HashMap will be able to find the object only if there is an object in HashMap which will have same hashCode and all fields are equal.

  • Hashcode of ninja250r object is calculated.
  • The index of array of Entry objects is determined based on hashcode of ninja250r.
  • In this case, the index will be 10 so 10th element is accessed. At this point it is known that ninja250r object can only be found in the same hashCode bucket as that of ninja250r.
  • Now 10th element is referring to a linked list. HashMap get method will try to find the ninja250r object.
  • First element in the list is cbr250r, although it has same hashCode as of ninja250r, it will not be equal because the manufacturer is different. So HashMap get method will go further and check for the next element in linked list.
  • Now next element is ninja250r, for this equals() method will return true. It means our desired object is found and retrieval is successful.

I hope the article helped understand how HashMap get method works.

Share Button

2 comments for “Working of HashMap Get Method

  1. December 14, 2016 at 3:52 pm

    sir… i have one doubt
    that is if manifacture is also same then which one will be called first

Leave a Reply

Your email address will not be published. Required fields are marked *