What data structures do HashMap, TreeMap, HashSet and TreeSet use internally?

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.

Key Points

HashMap Internal Technique

HashMap stores data using

How It Works

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.

Collision Handling

Before Java 8

Bucket

KeyA -> KeyB -> KeyC

After Java 8 (Heavy Collisions)

            KeyB
           /    \

KeyA KeyC

Technique Used

Average Complexity

TreeMap Internal Technique

TreeMap stores entries using a Red-Black Tree.

A Red-Black Tree is

Structure

              50
            /    \

30 70

/ \ / \

20 40 60 80

Each node stores

Technique Used

Complexity

HashSet Internal Technique

HashSet does not have its own storage structure.

Internally

HashSet uses HashMap.

Simplified Representation

HashSet<String> set =
        new HashSet<>();

Internally behaves like

HashMap<String, Object> map =
        new HashMap<>();

Stored Form

Key Value

Java PRESENT

Spring PRESENT

Only keys matter.

Values are dummy objects.

Technique Used

Complexity

TreeSet Internal Technique

TreeSet internally uses TreeMap.

Simplified Representation

TreeSet<Integer> set =
        new TreeSet<>();

Internally behaves like

TreeMap<Integer, Object> map =
        new TreeMap<>();

Stored Form

Key Value

10 PRESENT

20 PRESENT

30 PRESENT

Elements become TreeMap keys.

Technique Used

Complexity

Example

Suppose we store employee IDs.

HashSet

101, 102, 103

Internally

HashMap

101 → PRESENT

102 → PRESENT

103 → PRESENT

TreeSet

101, 102, 103

Internally

Red-Black Tree

         102
        /   \

101 103

Comparison Table

HashMap

TreeMap

HashSet

TreeSet

Interview Tip

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?

More Core Java - Level II interview questions

All Core Java - Level II questions