How HashMap get() Method Works Internally in Java
The get() method in HashMap is one of the most commonly used operations.
Although it looks like a simple key lookup, internally it involves hashing, bucket indexing,
and collision handling. In this article, we’ll break down the internal working of
HashMap.get() step by step with examples.
1. Hashing the Key
When you call map.get(key), the HashMap computes a hash value using the key’s
hashCode(). In Java 8+, this value is further processed with bitwise operations
to spread the hash bits and reduce collisions.
int hash = hash(key.hashCode());
2. Finding the Bucket
The hash value is then converted into an index in the internal array (called table) using:
int index = (n - 1) & hash; // n = table.length
This determines the bucket where the entry might be stored.
3. Searching Inside the Bucket
Each bucket can contain:
- null → no entry stored
- A single key-value pair
- A linked list of nodes (if multiple keys hash to the same bucket)
- A red-black tree (Java 8+, when collisions exceed threshold)
The get() method compares hash values and then checks key equality with equals().
4. Returning the Value
If a matching key is found, the corresponding value is returned.
If no entry exists in that bucket, null is returned.
5. Example Program
import java.util.HashMap;
public class HashMapGetExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 10);
map.put("banana", 20);
System.out.println(map.get("apple")); // 10
System.out.println(map.get("orange")); // null
}
}
6. Simplified Pseudo-code of get()
public V get(Object key) {
int hash = hash(key.hashCode());
int index = (n - 1) & hash;
Node<K,V> e = table[index];
while (e != null) {
if (e.hash == hash && (e.key.equals(key))) {
return e.value;
}
e = e.next; // move through linked list / tree
}
return null;
}
7. Performance
- Average Case: O(1)
- Worst Case: O(log n) if bucket is a tree, or O(n) if it’s a linked list (pre-Java 8)
🔑 Key Takeaways
get()relies on bothhashCode()andequals().- Efficient hash distribution improves lookup performance.
- Java 8 introduced tree buckets to optimize worst-case scenarios.
Comments
Post a Comment