How does hashmap work in Java?

Source: Internet
Author: User
How hashmap works in Java How hashmap works in JavaHow hashmap works in Java or sometime how get method work in hashmap is
Common Questions on Java interviews now days. Almost everybody who worked in Java knows about hashmap, where to use hashmap ordifference between hashtable and hashmap
Then why this interview question becomes so special? Because of the depth it offers. It has become very popular Java interview question in almost any senior or mid-senior level Java interviews. Investment Banks mostly prefer to ask this question and some time
Even ask to implement your own hashmap based upon your coding aptitude. introduction of concurrenthashmap and other concurrent collections has also made this questions as starting point to delve into more advanced feature. let's start the journey. questions start with simple statement

"Have you used hashmap before"Or"What is hashmap? Why do we use it"Almost everybody answers this with yes and then interviewee keep talking about common facts about hashmap likehashmap accept null while hashtable doesn' t, hashmap
Is not synchronized, hashmap is fast and so on along with basics like its stores key and value pairs etc. this shows that person has used hashmap and quite familiar with the functionality hashmap offers but interview takes a sharp turn from here and next
Set of follow-up questions gets more detailed about fundamentals involved with hashmap in Java. INTERVIEWER struck back with questions like"Do you know how hashmap works in Java"Or"How does get () method of hashmap works in Java"And then you get answers like I don't bother its standard Java API, you better look code on Java source or open JDK; I can find it out in Google at any time etc. but some interviewee definitely answer this and will say"Hashmap works on principle
Of hashing
, We have put (Key, value) and get (key) method for storing and retrieving objects from hashmap. when we pass key and value object to put () method on Java hashmap, hashmap implementation callshashcode
Method on key object and applies returned hashcode into its own hashing function to find a bucket location for storing entry object, important point to mention is that hashmap in Java stores both key and value object as map. entry in bucket which is essential
To understand the retrieving logic. if people fails to recognize this and say it only stores value in the bucket they will fail to explain the retrieving logic of any object stored in Java hashmap. this answer is very much acceptable and does make sense that
Interviewee has fair bit of knowledge on how hashing works and how hashmap works in Java. but this is just start of story and confusion increases when you put interviewee on scenarios faced by Java developers on day by day basis. next question cocould be about
Collision Detection and Collision Resolution in Java hashmap e.g."What will happen if two different objects have same hashcode ?"Now from here onwards real confusion starts, some time candidate will say that since hashcode is equal, both objects are equal and hashmap will throw exception or not store them again etc, then you might want to remind them aboutequals ()
And hashcode () contract that two unequal object in Java can have same hashcode. some will give up at this point and few will move ahead and say "since hashcode is same, bucket location wocould be same and collision will occur in hashmap, since hashmap use
Please list to store object, this entry (Object of map. Entry comprise key and value) will be stored infound list. Great this answer make sense though there are missing
Collision Resolution methods available this is simplest and hashmap in Java does follow this. But story does not end here and interviewer asks"How will you retrieve value object if two keys will have same hashcode ?"Interviewee
Will say we will call get () method and then hashmap uses key object's hashcode To Find Out bucket location and retrieves value object but then you need to remind him that there are two value objects are stored in Same bucket, so they will say abouttraversal
In each list until we find the value object, then you askHow do you identify value object because you don't have value object to compare, Until they know that hashmap stores both key and value in each list node or as map. Entry they won't
Be able to resolve this issue and will try and fail. But those bunch of people who remember this key information will say that after finding bucket location, we willCall keys. Equals () methodTo identify correct node in your list and return associated value object for that key in Java hashmap
. Perfect this is the correct answer. In seconds cases interviewee fails at this stage because they get confused betweenhashcode () andequals ()
Or keys and values object in Java hashmap which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from hashmap in Java. some good developer point out
Here that using immutable,
Final object with proper equals () and hashcode () Implementation wocould act as perfect Java hashmap keys andImprove Performance of Java hashmap by using cing collision. ImmutabilityAlso allows caching there hashcode of different keys
Which makes overall retrieval process very fast and suggest that
String and various Wrapper Classes e.g. Integer very good keys in Java hashmap. Now if you clear this entire Java hashmap interview, you will be surprised by this very interesting question"What happens on hashmap in Java if the size of the hashmap exceeds a given threshold defined by load factor? ". Until you know
How hashmap works exactly you won't be able to answer this question. if the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is. 75 it will act to re-size the map once it fills 75%. similar to other collection classes
Like
Arraylist, Java hashmap re-size itself by creating a new bucket array of size twice of previous size of hashmap, and then start putting every old element into that new bucket array. this process is called rehashing because it also applies Hash Function
To find new bucket location. If you manage to answer this question on hashmap in Java you will be greeted"Do you see any problem with resizing of hashmap in Java"
, You might not be able to pick the context and then he will try to give you hint about multiple thread accessing the Java hashmap and potentially lookingRace Condition on hashmap in Java. So the answer is yes there is potential
Race condition exists while resizing hashmap in Java, if two
Thread at the same time found that now hashmap needs resizing and they both try to resizing. on the process of resizing of hashmap in Java, the element in bucket which is stored in linked list get reversed in order during there migration to new bucket
Because Java hashmap doesn' t append the new element at tail instead it append new element at headTo avoid tail traversing. If Race Condition happens then you will end up with an infinite loop. Though this point you can potentially argue that what
The hell makes you think to use hashmap in multi-threaded environment to interviewer few more question on hashmap in Java which is contributed by readers of javarevisited blog:1) Why string, integer and other Wrapper Classes are considered good keys?String, integer and other Wrapper Classes are natural candidates of hashmap key, and string is most frequently used key as well becausestring is immutable and final, and
Overrides equals and hashcode () method. other Wrapper class also shares similar property. immutabiility is required, in order to prevent changes on fields used to calculate hashcode () because if key object return different hashcode during insertion and Retrieval
Than it won't be possible to get object from hashmap. immutability is best as it offers other advantages as well likethread-safety, if you can keep your hashcode
Same by only making certain fieldsfinal, then you go for that as well. Since equals () and hashcode () method is used during reterival of value object from hashmap,
Its important that key object correctly override these methods and follow contact. If unequal object return different hashcode than chances of collision will be less which subsequently improve performance of hashmap.2) Can we use any custom object as key in hashmap?This is an extension of previous questions. Ofcourse you can use any object as key in Java hashmap provided it follows equals and hashcode Contract and Its hashcode shocould not vary once the object is inserted into map.
If custom object is immutable than this will be already taken care because you can not change it once created.3) Can we use concurrenthashmap in place of hashtable?This is another question which getting popular due to increasing popularity of capacity. Since we know hashtable is synchronized but provided provides better concurrency by only locking portion of map determined by concurrency level.
Concurrenthashmap is certainly introduced as hashtable and can be used in place of it but hashtable provide stronger thread-safety than concurrenthashmap. See my postdifference
Between hashtable and concurrenthashmap for more details.

 

Personally, I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this hashmap questions has verified
  • Concept of hashing
  • Collision Resolution in hashmap
  • Use of equals () and hashcode () And there importance in hashmap?
  • Benefit of immutable object?
  • Race Condition on hashmap in Java
  • Resizing of Java hashmap
Just to summarize here are the answers which does makes sense for above questions How hashmap works in JavaHashmap works on principle of hashing, we have put () and get () method for storing and retrieving object form hashmap. when we pass an both key and value to put () method to store on hashmap, it uses key object hashcode () method to calculate hashcode and
They by applying hashing on that hashcode it identifies bucket location for storing value object. while retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. hashmap uses linked list
In case of collision and object will be stored in next node of linked list. Also hashmap stores both key + value tuple in every node of linked list. What will happen if two different hashmap key objects have same hashcode?They will be stored in Same bucket but no next node of linked list. and keys equals () method will be used to identify correct key value pair in hashmap. in terms of usage Java hashmap is very versatile and I have mostly used hashmap as cache in electronic trading application I have worked. since finance domain used Java heavily and due to performance reason we need caching hashmap and concurrenthashmap
Comes as very handy there. You can also check following articles form javarevisited to learn more about hashmap and hashtable in Java: Read more:

Http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html#ixzz2ZTyBCtq9

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.