HashMap work internally in Java?" Many candidates struggle to explain the internal implementation of HashMap clearly, which can negatively impact their interview performance.This question helps interviewers assess a candidate's understanding of the Java Collections Framework and core Java concepts. Therefore, it should be on your preparation checklist before attending any Core Java interview.
HashMap works on the principle of hashing. To understand how HashMap works internally, you should first be familiar with the following concepts:
Hash Function
Hash Value (Hash Code)
Bucket
What Are a Hash Function, Hash Value, and Bucket?
ThehashCode() method is the hash function in Java that returns an integer value representing an object. One important point to note is that this method is defined in the Object class, which is the superclass of all Java classes.The following is the implementation (method declaration) of the hashCode() method in the Object class:
public native int hashCode();
hashCode() method returns an int value.The integer value returned by the hashCode() method is known as the hash value (or hash code) of the object.
What is bucket ?
A bucket is used to store key-value pairs in a
HashMap. A single bucket can contain multiple key-value pairs if multiple keys are mapped to the same bucket due to a hash collision. In a HashMap, each bucket is internally represented as a linked list. Starting from Java 8, when the number of entries in a bucket exceeds a threshold, the linked list is converted into a Red-Black Tree to improve performance.Before understanding the internal working of HashMap, you should be familiar with the following important concepts:
Two unequal objects can return the same
hashCode().If two objects are equal according to the
equals()method, they must return the samehashCode().
HashMap primarily uses the following two methods to store and retrieve data:
put()– Stores a key-value pair in theHashMap.get()– Retrieves the value associated with a given key.
1) How put(Key key, Value v) method works internally?
put() method:public V put(K key, V value) {
if (key == null)
Nreturn putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<k , V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
Let's understand the above code step by step.
The key is first checked for
null. If the key isnull, the entry is stored in bucket index0because the hash code for anullkey is always treated as0.If the key is not
null, the key'shashCode()method is called to generate the hash code. This hash code is used to determine the bucket index where the entry should be stored. Since a poorly implementedhashCode()method may not distribute keys uniformly,HashMapapplies an additional hash function to spread the hash values more evenly across the buckets, reducing the chances of collisions.The processed hash value is then used to calculate the bucket index in the internal table array. In older JDK versions, this was done using the
indexFor(hash, table.length)method.The
indexFor()method calculates the bucket index based on the hash value and the length of the table array. Internally, it performs a bitwise AND (&) operation to determine the appropriate bucket index, as shown below:
static int indexFor(int h, int length) { return h & (length-1); }
- If two key objects produce the same hash code (a situation known as a hash collision), they are stored in the same bucket as a linked list. Therefore,
HashMapiterates through the linked list to check whether the key already exists before inserting a new entry.
2) How get(Key key) method works internally?
The following steps are performed when you call the
get() method with a key to retrieve the corresponding value from a hash-based collection such as HashMap.Let's look at the code:
public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
The key is first checked for
null. If the key isnull,HashMapreturns the value associated with thenullkey, which is stored in bucket index0.If the key is not
null, the key'shashCode()method is called to compute its hash code.The hash code is then used to calculate the bucket index in the internal table array (using the hash and the table size) to locate the appropriate bucket.
After locating the bucket,
HashMaptraverses the linked list (or Red-Black Tree in Java 8 and later) and compares the given key with each stored key using theequals()method. If a matching key is found, the corresponding value is returned; otherwise,nullis returned.
What happens if two keys has same hashCode?
If multiple keys produce the same
hashCode(), a hash collision occurs during the put() operation. This means that multiple entries are stored in the same bucket. Each entry maintains a reference to the next entry, forming a linked list. (In Java 8 and later, if the number of entries in a bucket exceeds a certain threshold, the linked list is converted into a Red-Black Tree.)When retrieving a value in this situation, HashMap performs the following steps:
It calls the
hashCode()method of the key to determine the bucket index.It traverses the linked list (or Red-Black Tree) in that bucket and compares the search key with each stored key using the
equals()method.When
equals()returnstrue,HashMapreturns the corresponding value associated with that key.
This is why it is important to correctly override both the hashCode() and equals() methods when using custom objects as keys in a HashMap.
Key Notes:--
The data structure used to store entries in a HashMap is an array named table, whose elements are of type Node (called Entry in Java 7 and earlier).
Each index in the array is called a bucket because it can hold the first node of a linked list (or a Red-Black Tree in Java 8 and later when the bucket becomes heavily populated).
The key object's hashCode() method is used to compute the bucket index where the key-value pair should be stored.
The key object's equals() method is used to ensure the uniqueness of keys in the HashMap and to identify the correct entry during retrieval.
The value object's hashCode() and equals() methods are not used by the HashMap's put() and get() operations. Only the key's hashCode() and equals() methods are used.
The hash code for a null key is always treated as 0. Therefore, the entry with a null key is always stored in bucket index 0.
The data structure used to store entries in a HashMap is an array named table, whose elements are of type Node (called Entry in Java 7 and earlier).
Each index in the array is called a bucket because it can hold the first node of a linked list (or a Red-Black Tree in Java 8 and later when the bucket becomes heavily populated).
The key object's hashCode() method is used to compute the bucket index where the key-value pair should be stored.
The key object's equals() method is used to ensure the uniqueness of keys in the HashMap and to identify the correct entry during retrieval.
The value object's hashCode() and equals() methods are not used by the HashMap's put() and get() operations. Only the key's hashCode() and equals() methods are used.
The hash code for a null key is always treated as 0. Therefore, the entry with a null key is always stored in bucket index 0.
Related Posts:--
1) Internal Implementation of TreeMap in Java
2) How to iterate the TreeMap in reverse order in Java
3) Java Program to Count Occurrence of Word in a Sentence
4) Internal implementation of ArrayList in Java
5) String Interview Questions and Answers
6) Exception Handling Interview questions and answers
so why i get such output?
ReplyDeleteimport java.util.HashMap;
public class StudentDemo {
String name;
int id;
public StudentDemo() {
name = null;
id = 0;
}
public StudentDemo( String name , int id){
this.name = name;
this.id = id;
}
public static void main(String arh[]){
StudentDemo s1 = new StudentDemo("shramik",121);
StudentDemo s2 = new StudentDemo("rohit",122);
StudentDemo s3 = new StudentDemo("suresh",123);
StudentDemo s4 = new StudentDemo("karan",124);
StudentDemo s5 = new StudentDemo("pratik",125);
StudentDemo s6 = new StudentDemo("mohan",126);
//System.out.println(s1.hashCode()+" "+s2.hashCode()+" "+s3.hashCode()+" "+s4.hashCode()+" "+s5.hashCode()+" "+s6.hashCode());
HashMap hm = new HashMap();
hm.put(s1,"8982xxxxxx");
hm.put(s2,"8934xxxxxx");
hm.put(s3,"9922xxxxxx");
hm.put(s4,"9835xxxxxx");
hm.put(s5,"8089xxxxxx");
hm.put(s6,"5678xxxxxx");
hm.put(new StudentDemo("abc",127),"8934xxxxxx");
System.out.println(hm.get(s1));
System.out.println(hm.get(s2));
System.out.println(hm.get(s3));
System.out.println(hm.get(s4));
System.out.println(hm.get(s5));
System.out.println(hm.get(s6));
System.out.println(hm.get(new StudentDemo("abc",127)));
}
}
o/p:-
8982xxxxxx
8934xxxxxx
9922xxxxxx
9835xxxxxx
8089xxxxxx
5678xxxxxx
null
i am not override the hashCode() and equals() method also i invoke get(key) method on hashmap object i get respected value but for last key not why?
In the above case, While creating new class object you must override the hashCode() and equals() method. While creating new object it will create new hash code that won't match with existing hash code so it will return null
ReplyDeleteOne of the most important question of the core java interviewers is How hash map works in java or internal.implementation of hashmap. Most of the candidates rejection chances increases if the candidate do not give the satisfactory explanation . This question shows that candidate has good knowledge of Collection . So this question should be in your to do list before appearing for the interview .
ReplyDeleteThanks for helping me to understand basic concepts. As a beginner in Java programming your post help me a lot.Thanks for your informative article.
Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
java training in chennai |
java training institutes in chennai