How HashMap works in Java
How HashMap works in Java or do you know Hashmap in java is one of the most asked interview question in java. It checks your knowledge about the collection as HashMap is one of the mostly used Collection class. Also I would like to mention another favorite interview question which is "what is the difference between Hashtable and HashMap?" But this really doesn’t test the knowledge about Collection. So it is important to know How HashMap works in java?
Before jumping into what the interviewer ask about the HashMap lets first try to understand what exactly the HashMap is. One minute before going to check, How HashMap works in Java? I would like you to check article about equals() and Hashcode().
What the HashMap is?
HashMap class comes from java.util package and HashMap class extends AbstractMap and implements Map, Cloneable and Serializable interfaces. HashMap is nothing but Hash table based implementation of Map Interface. So for question How HashMap works in Java, the answer is on principle of Hashing.
The HashMap implementation has some of the characteristics such as :
1. HashMap provides all of the optional map operations.
2. HashMap permits null keys as well as null values.
3. Order is not maintained in HashMap.
HashMap works on principle of Hashing i.e. it has put method for storing the key value pair and get method to retrieve the value.
put() method in java HashMap
We need to pass Key and Value object to put() method in Java HashMap. Once we pass the key and value to in put() method of HashMap, HashMap calls hashCode method on key object and use hashcode into own hashing function to find the bucket location. Bucket is the place where Entry object is stored and hashcode is like an address of that bucket. So what exactly we store in bucket? This is very important to understand. Java stores both Key and Value object as a Map.Entry in bucket. These are stored like LinkedList. But why these are stored as LinkedList. As we know we are using the hashcode to find the bucket location but two unequal objects can have same hashcode. So there are chances of collision. So along with value key is stored.
get() method in java HashMap
We need to pass key to the get method which takes the key as an argument and try to find bucket position using the hashcode. Once it finds the bucket using equals function it gets the value and returns it.