HashMap, TreeMap, HashSet, and TreeSet use different internal data structures and algorithms to achieve efficient storage, retrieval, insertion, and deletion operations. Understanding these internal implementations helps explain their performance characteristics and appropriate use cases.
HashMap Internal Technique
1. hashCode() generates a hash value.
2. HashMap determines the bucket index.
3. The entry is stored in that bucket.
4. equals() is used to identify the exact key.
Bucket
KeyA -> KeyB -> KeyC
KeyB
/ \KeyA KeyC
TreeMap Internal Technique
TreeMap stores entries using a Red-Black Tree.
50
/ \30 70
/ \ / \
20 40 60 80
HashSet Internal Technique
HashSet does not have its own storage structure.
HashSet uses HashMap.
HashSet<String> set =
new HashSet<>();HashMap<String, Object> map =
new HashMap<>();Key Value
Java PRESENT
Spring PRESENT
Only keys matter.
Values are dummy objects.
TreeSet Internal Technique
TreeSet internally uses TreeMap.
TreeSet<Integer> set =
new TreeSet<>();TreeMap<Integer, Object> map =
new TreeMap<>();Key Value
10 PRESENT
20 PRESENT
30 PRESENT
Elements become TreeMap keys.
Suppose we store employee IDs.
101, 102, 103
HashMap
101 → PRESENT
102 → PRESENT
103 → PRESENT
101, 102, 103
Red-Black Tree
102
/ \101 103
Comparison Table
A concise interview answer is
HashMap uses hashing with an array of buckets and handles collisions using Linked Lists or Red-Black Trees. TreeMap uses a Red-Black Tree to maintain sorted key-value pairs. HashSet is internally backed by a HashMap and stores elements as keys, while TreeSet is backed by a TreeMap and stores elements in a Red-Black Tree structure. These internal implementations determine their ordering behavior and performance characteristics.
Last updated: 11 November 2026
Previous question: What is the time complexity of insertion, deletion and retrieval in TreeSet and TreeMap?
Next question: What is a design pattern in Java, and why do we use design patterns?