Results for Collections

HashMap vs Hashtable in Java with Real Examples

3:26 PM

HashMap and Hashtable are two important Map implementations in Java. Both store data in key-value pairs and use hashing internally, but they differ significantly in terms of synchronization, performance, null handling, and modern usage.



Understanding the differences between HashMap and Hashtable is a common interview topic and can help developers select the appropriate collection for their applications.

What is HashMap?

HashMap is a part of the Java Collections Framework introduced in Java 1.2. It provides high-performance data storage using key-value pairs and is not synchronized.


Map<Integer, String> map = new HashMap<>();

map.put(1, "Java");
map.put(2, "Spring");

System.out.println(map);

What is Hashtable?

Hashtable is a legacy collection class introduced before the Collections Framework. It stores data using key-value pairs and provides thread safety through synchronization.


Hashtable<Integer, String> table =
        new Hashtable<>();

table.put(1, "Java");
table.put(2, "Spring");

System.out.println(table);

Major Differences Between HashMap and Hashtable

Feature HashMap Hashtable
Introduced In Java 1.2 Java 1.0
Thread Safe No Yes
Synchronized No Yes
Performance Faster Slower
Null Keys One Allowed Not Allowed
Null Values Multiple Allowed Not Allowed
Legacy Collection No Yes

Null Key Example in HashMap


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

map.put(null, "Java");

System.out.println(map);

Output


{null=Java}

HashMap allows one null key.

Null Key Example in Hashtable


Hashtable<Integer,String> table =
        new Hashtable<>();

table.put(null, "Java");

Output


Exception in thread "main"
java.lang.NullPointerException

Hashtable does not allow null keys.

Why Hashtable Is Slower

Hashtable synchronizes every method. Only one thread can access the object at a time.


public synchronized V put(K key, V value)

Because of synchronization overhead, Hashtable is slower than HashMap in most applications.

Thread Safety Example

Hashtable provides built-in synchronization.


Hashtable<Integer,String> table =
        new Hashtable<>();

table.put(1, "Java");
table.put(2, "Spring");

Multiple threads can work safely with Hashtable, although performance may suffer.

HashMap in Multi-Threaded Applications

HashMap is not thread-safe. Concurrent modifications may lead to inconsistent results.


Map<Integer,String> map =
        new HashMap<>();

For modern multi-threaded applications, ConcurrentHashMap is generally preferred.

Internal Working

Both HashMap and Hashtable use hashing techniques internally.

The process:

  1. Calculate hashCode().
  2. Find bucket location.
  3. Store the entry in the bucket.
  4. Use equals() when required.

HashMap received significant performance improvements in Java 8 through treeification. Hashtable did not receive equivalent modern enhancements.

Performance Comparison

Operation HashMap Hashtable
put() Fast Slower
get() Fast Slower
remove() Fast Slower

HashMap is normally preferred when synchronization is not required.

Modern Alternative to Hashtable

Instead of Hashtable, modern Java applications usually use:


ConcurrentHashMap

ConcurrentHashMap provides thread safety with significantly better performance.


ConcurrentHashMap<Integer,String> map =
        new ConcurrentHashMap<>();

map.put(1, "Java");
map.put(2, "Spring");

Real Interview Questions

Which is faster: HashMap or Hashtable?

HashMap is generally faster because it does not synchronize every operation.

Is Hashtable thread-safe?

Yes. Hashtable synchronizes its methods and is thread-safe.

Can HashMap store null keys?

Yes. One null key and multiple null values are allowed.

Can Hashtable store null keys?

No. Hashtable throws NullPointerException.

Real World Recommendation

  • Use HashMap for single-threaded applications.
  • Use ConcurrentHashMap for modern multi-threaded applications.
  • Avoid Hashtable in new projects.
  • Understand Hashtable because it is still asked in interviews.

Common Interview Questions

Why is Hashtable considered legacy?

Hashtable was introduced before the Collections Framework and has largely been replaced by newer implementations.

Why is HashMap preferred today?

Better performance, support for nulls, and integration with modern collection APIs.

Which collection should replace Hashtable?

ConcurrentHashMap is typically recommended for thread-safe requirements.

Do HashMap and Hashtable use hashing internally?

Yes. Both rely on hashing for data storage and retrieval.

Frequently Asked Questions (FAQ)

Can HashMap be synchronized?

Yes. It can be wrapped using Collections.synchronizedMap().


Map<Integer,String> map =
Collections.synchronizedMap(
        new HashMap<>());

Which one should be used in modern applications?

HashMap for non-concurrent applications and ConcurrentHashMap for concurrent applications.

Does Hashtable maintain insertion order?

No. Hashtable does not guarantee insertion order.

Can Hashtable contain duplicate keys?

No. Like all Map implementations, keys must be unique.

Conclusion

HashMap and Hashtable may appear similar, but they serve different purposes. HashMap provides better performance and flexibility, while Hashtable offers built-in synchronization at the cost of speed. In modern Java development, HashMap and ConcurrentHashMap are almost always preferred, but understanding Hashtable remains important for interviews and legacy systems.

Keywords

HashMap vs Hashtable, Difference Between HashMap and Hashtable, Hashtable Interview Questions, HashMap Interview Questions, Thread Safe Collections Java, HashMap vs ConcurrentHashMap, Java Collections Framework, Hashtable Internal Working, HashMap Internal Working, Java Collection Interview Questions, Hashtable Example, HashMap Null Key, Legacy Collections Java, Core Java Interview Questions, Java Map Implementations

HashMap vs Hashtable in Java with Real Examples HashMap vs Hashtable in Java with Real Examples Reviewed by 13thGhost on 3:26 PM Rating: 5

Fail-Fast vs Fail-Safe Iterator in Java with Examples

3:20 PM

Fail-Fast and Fail-Safe iterators are among the most frequently asked Java Collections Framework interview topics. Many developers have encountered ConcurrentModificationException but do not fully understand why it occurs.

In this article, we will learn what Fail-Fast and Fail-Safe iterators are, how they work internally, their differences, and how to avoid ConcurrentModificationException in real-world applications.

What is an Iterator?

An Iterator is used to traverse elements stored in Java collections. It provides a standard way to access collection elements one by one.


List<String> technologies =
        new ArrayList<>();

technologies.add("Java");
technologies.add("Spring Boot");
technologies.add("Kafka");

Iterator<String> iterator =
        technologies.iterator();

while(iterator.hasNext()) {
    System.out.println(iterator.next());
}

Output


Java
Spring Boot
Kafka

What is a Fail-Fast Iterator?

Fail-Fast iterators immediately throw a ConcurrentModificationException if the collection is structurally modified while iterating.

Most collection classes provide Fail-Fast iterators.

  • ArrayList
  • HashMap
  • HashSet
  • LinkedList
  • TreeMap

Example of a Fail-Fast Iterator


List<String> list = new ArrayList<>();

list.add("Java");
list.add("Spring");
list.add("Kafka");

for(String technology : list) {

    if("Spring".equals(technology)) {
        list.remove(technology);
    }
}

Output


Exception in thread "main"
java.util.ConcurrentModificationException

The collection was modified while iteration was in progress. Therefore the iterator immediately failed.

Why Does ConcurrentModificationException Occur?

Most collection classes maintain an internal variable called modCount.

Whenever the collection structure changes, modCount is updated. The iterator stores the expected modification count when iteration begins.

During traversal:

  • If modCount equals expectedModCount, iteration continues.
  • If modCount changes unexpectedly, ConcurrentModificationException is thrown.

Simplified Internal Logic


if(modCount != expectedModCount) {
    throw new ConcurrentModificationException();
}

This mechanism helps detect accidental modifications.

Modifying Collection Correctly

Instead of modifying the collection directly, use Iterator.remove().


List<String> list = new ArrayList<>();

list.add("Java");
list.add("Spring");
list.add("Kafka");

Iterator<String> iterator =
        list.iterator();

while(iterator.hasNext()) {

    String value = iterator.next();

    if("Spring".equals(value)) {
        iterator.remove();
    }
}

System.out.println(list);

Output


[Java, Kafka]

This works correctly because the iterator is aware of the modification.

What is a Fail-Safe Iterator?

Fail-Safe iterators operate on a copy of the collection rather than the original collection.

Because iteration occurs on a separate copy, modifications to the original collection do not cause ConcurrentModificationException.

Example of Fail-Safe Iterator


ConcurrentHashMap<Integer, String> map =
        new ConcurrentHashMap<>();

map.put(1, "Java");
map.put(2, "Spring");

for(Integer key : map.keySet()) {

    map.put(3, "Kafka");

    System.out.println(key);
}

No ConcurrentModificationException is thrown.

Collections That Provide Fail-Safe Behaviour

  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet

CopyOnWriteArrayList Example


CopyOnWriteArrayList<String> list =
        new CopyOnWriteArrayList<>();

list.add("Java");
list.add("Spring");

for(String value : list) {

    list.add("Kafka");

    System.out.println(value);
}

Iteration continues without throwing ConcurrentModificationException.

Fail-Fast vs Fail-Safe

Feature Fail-Fast Fail-Safe
Throws ConcurrentModificationException Yes No
Works On Original Collection Yes No
Works On Copy No Yes
Memory Usage Low Higher
Performance Faster Slightly Slower
Thread Safe No Generally Safer

Fail-Fast Collections


ArrayList
LinkedList
HashSet
TreeSet
HashMap
TreeMap
LinkedHashMap

Fail-Safe Collections


ConcurrentHashMap
CopyOnWriteArrayList
CopyOnWriteArraySet

Real World Example

Suppose an e-commerce application maintains active user sessions. Multiple threads may read and update session information simultaneously.

Using ConcurrentHashMap makes more sense because modifications can occur while iteration is in progress.





Common Interview Questions

What is ConcurrentModificationException?

It is an exception thrown when a collection is modified while a Fail-Fast iterator is traversing it.

Does Fail-Fast guarantee an exception every time?

No. It is a best-effort mechanism designed to detect accidental modifications.

Is ConcurrentHashMap Fail-Fast?

No. ConcurrentHashMap provides Fail-Safe behaviour.

Why is Fail-Safe called Fail-Safe?

Because it does not fail when the underlying collection is modified during iteration.

Best Practices

  • Do not modify collections directly during iteration.
  • Use Iterator.remove() when removal is required.
  • Use ConcurrentHashMap for concurrent access scenarios.
  • Use CopyOnWriteArrayList when reads greatly outnumber writes.
  • Understand iterator behaviour before using collections in multi-threaded environments.

Frequently Asked Questions (FAQ)

Can ArrayList throw ConcurrentModificationException?

Yes. ArrayList uses a Fail-Fast iterator.

Can ConcurrentHashMap throw ConcurrentModificationException?

Typically no. It provides Fail-Safe behaviour.

Which iterator should be used in multi-threaded applications?

Fail-Safe iterators are generally preferred in multi-threaded environments.

Is Iterator.remove() safe?

Yes. It updates the collection in a way that the iterator understands.

Conclusion

Understanding the difference between Fail-Fast and Fail-Safe iterators is essential for every Java developer. Fail-Fast iterators help detect unintended modifications, while Fail-Safe iterators support concurrent updates safely. Knowing when to use each approach can prevent runtime errors and improve application reliability.

Keywords

Fail Fast Iterator Java, Fail Safe Iterator Java, ConcurrentModificationException, Iterator Interview Questions, Java Collections Framework, ArrayList Iterator, ConcurrentHashMap Iterator, CopyOnWriteArrayList, Fail Fast vs Fail Safe, Java Multithreading Collections, Iterator remove Method, Concurrent Collections Java, Core Java Interview Questions, Collections Framework Tutorial, Java Iterator Examples

Fail-Fast vs Fail-Safe Iterator in Java with Examples Fail-Fast vs Fail-Safe Iterator in Java with Examples Reviewed by 13thGhost on 3:20 PM Rating: 5

equals() vs hashCode() in Java with Real Examples

3:07 PM

The equals() and hashCode() methods are among the most frequently asked topics in Java interviews. They play a critical role in Java Collections Framework, especially when working with HashMap, HashSet and other hash-based collections.

Many developers override one of these methods but forget to override the other, resulting in unexpected bugs and inconsistent behaviour. In this article, we will understand how equals() and hashCode() work, the contract between them, and why both methods are important.

What is equals() Method?

The equals() method is defined in the Object class and is used to compare two objects for equality.

Default implementation:


public boolean equals(Object obj) {
    return (this == obj);
}

By default, equals() compares object references, not object contents.

Example Without Overriding equals()


class Employee {

    int id;

    Employee(int id) {
        this.id = id;
    }
}

public class Test {

    public static void main(String[] args) {

        Employee e1 = new Employee(100);
        Employee e2 = new Employee(100);

        System.out.println(e1.equals(e2));
    }
}

Output


false

Even though both employees have the same id, they are different objects in memory.

Overriding equals()


class Employee {

    int id;

    Employee(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object obj) {

        if(this == obj)
            return true;

        if(obj == null || getClass() != obj.getClass())
            return false;

        Employee emp = (Employee)obj;

        return this.id == emp.id;
    }
}

Output


true

Now the comparison is based on object content rather than memory location.

What is hashCode() Method?

hashCode() returns an integer value that represents the hash code of an object.

Java collections such as HashMap and HashSet use hashCode() to determine where an object should be stored.


String language = "Java";

System.out.println(language.hashCode());

Why Do We Need hashCode()?

Imagine a library with thousands of books. Instead of checking every shelf, books are placed in specific sections based on categories.

Similarly, hashCode() helps Java quickly locate objects inside hash-based collections.

The Contract Between equals() and hashCode()

Java defines an important contract:

  • If two objects are equal according to equals(), they must have the same hashCode().
  • If two objects have the same hashCode(), they are not necessarily equal.
  • If equals() is overridden, hashCode() should also be overridden.



Incorrect Implementation Example

Only equals() is overridden:


class Employee {

    int id;

    Employee(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object obj) {

        Employee emp = (Employee)obj;

        return this.id == emp.id;
    }
}

This may cause problems when using HashSet and HashMap.

HashSet Problem Example


Set<Employee> employees =
        new HashSet<>();

employees.add(new Employee(1));
employees.add(new Employee(1));

System.out.println(employees.size());

Expected Output


1

Actual Output


2

Because hashCode() was not overridden, Java places both objects into different buckets.

Correct Implementation


class Employee {

    int id;

    Employee(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object obj) {

        if(this == obj)
            return true;

        if(obj == null ||
           getClass() != obj.getClass())
            return false;

        Employee emp = (Employee)obj;

        return this.id == emp.id;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(id);
    }
}

Now HashSet correctly treats duplicate employees as identical objects.

How HashMap Uses equals() and hashCode()

HashMap first uses hashCode() to find the bucket.

After locating the bucket, equals() is used to identify the exact object.


Map<Employee, String> map =
        new HashMap<>();

Employee e1 = new Employee(1);

map.put(e1, "Java Developer");

Employee e2 = new Employee(1);

System.out.println(map.get(e2));

Without proper equals() and hashCode() implementations, retrieval may fail.

Real Interview Question

Can Two Different Objects Have the Same hashCode()?

Yes. This situation is known as a hash collision.


"Aa".hashCode()
"BB".hashCode()

These strings produce the same hash code but are different objects.

Real Interview Question

Can Equal Objects Have Different hashCodes?

No. Equal objects must always produce the same hashCode().

Violating this rule breaks the contract between equals() and hashCode().

equals() vs == Operator

equals() ==
Compares content Compares references
Can be overridden Cannot be overridden
Works on object state Works on memory addresses

Example


String s1 = new String("Java");
String s2 = new String("Java");

System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

Output


false
true

Best Practices

  • Always override equals() and hashCode() together.
  • Use the same fields in both methods.
  • Prefer using Objects.hash() for simplicity.
  • Test custom objects before storing them in HashMap and HashSet.

Using Objects.hash()


@Override
public int hashCode() {
    return Objects.hash(id);
}

This approach is cleaner and easier to maintain.

Common Interview Questions

Why should hashCode() be overridden when equals() is overridden?

Because collections such as HashMap and HashSet depend on hashCode() for bucket selection.

What happens if only equals() is overridden?

Collections may store duplicate objects or fail to retrieve existing objects.

Can two objects have the same hashCode()?

Yes. This is called a hash collision.

Can equal objects have different hashCodes?

No. This violates Java's contract.

Frequently Asked Questions (FAQ)

Which collections rely heavily on equals() and hashCode()?

HashMap, HashSet, Hashtable, LinkedHashMap, and LinkedHashSet.

What is a hash collision?

A hash collision occurs when two different objects generate the same hash code.

Does TreeMap use hashCode()?

No. TreeMap relies on comparison logic and Red-Black Tree structure instead of hashing.

What is the most common mistake with equals() and hashCode()?

Overriding equals() but forgetting to override hashCode().

Conclusion

The equals() and hashCode() methods are fundamental concepts in Java. While equals() determines object equality, hashCode() helps collections efficiently organize and retrieve data. Understanding their relationship is essential for working with HashMap, HashSet, and many other Java collections. Mastering these concepts will help avoid subtle bugs and significantly improve interview performance.

Keywords

equals vs hashCode Java, hashCode Interview Questions, equals Method Java, Java Object Class Methods, HashMap equals hashCode, HashSet equals hashCode, Java Collections Framework, equals vs Double Equals, hashCode Contract Java, Object Equality Java, Java Interview Questions, Hash Collision Java, Overriding equals and hashCode, Core Java Concepts, Java Best Practices

equals() vs hashCode() in Java with Real Examples equals() vs hashCode() in Java with Real Examples Reviewed by 13thGhost on 3:07 PM Rating: 5

LinkedList Internal Working in Java with Examples

2:37 PM

LinkedList is one of the most important collection implementations in Java. Unlike ArrayList, which stores elements in a dynamic array, LinkedList stores elements using nodes connected together. Understanding how LinkedList works internally is extremely important for Java interviews and for selecting the right collection in real-world applications.

In this article, we will explore the internal architecture of LinkedList, how insertion and deletion work, how nodes are connected, performance characteristics, and common interview questions.

What is LinkedList?

LinkedList is a class that implements both the List interface and Deque interface. It uses a doubly linked list internally to store and manage data.


List<String> technologies = new LinkedList<>();

technologies.add("Java");
technologies.add("Spring Boot");
technologies.add("Kafka");

System.out.println(technologies);

Output


[Java, Spring Boot, Kafka]

Important Characteristics of LinkedList

  • Maintains insertion order.
  • Allows duplicate elements.
  • Allows null values.
  • Uses a doubly linked list internally.
  • Efficient insertions and deletions.
  • Random access is slower compared to ArrayList.

Internal Structure of LinkedList

LinkedList stores data using nodes. Each node contains:


  • Data
  • Reference to previous node
  • Reference to next node

Simplified node structure:


class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;
}

How Nodes Are Connected


NULL
  ^
  |
[Java] <-> [Spring] <-> [Kafka]
                         |
                         v
                       NULL

Each node knows its previous and next node, which makes insertion and deletion easier.

How add() Works Internally


LinkedList<String> list =
        new LinkedList<>();

list.add("Java");
list.add("Spring");
list.add("Kafka");

When a new element is added:

  1. A new node is created.
  2. The new node becomes the last node.
  3. The previous last node is updated.
  4. Links between nodes are adjusted.

Example


Before:

[Java] <-> [Spring]

After adding Kafka:

[Java] <-> [Spring] <-> [Kafka]

How get() Works Internally

Unlike ArrayList, LinkedList cannot directly access an element using an index.


list.get(2);

Java must traverse the list node by node until the required index is reached.


Index 0 -> Java
Index 1 -> Spring
Index 2 -> Kafka

This traversal makes random access slower.

How remove() Works Internally


list.remove("Spring");

Java performs:

  1. Locate the target node.
  2. Update previous node's next reference.
  3. Update next node's previous reference.
  4. Remove the target node.

Before Removal


Java <-> Spring <-> Kafka

After Removal


Java <-> Kafka

Adding Elements at the Beginning

LinkedList performs very efficiently when inserting elements at the start.


LinkedList<String> list =
        new LinkedList<>();

list.addFirst("Java");
list.addFirst("Spring");

Output


[Spring, Java]

Adding Elements at the End


list.addLast("Kafka");

LinkedList maintains references to both head and tail nodes, making this operation efficient.

LinkedList as Queue


Queue<String> queue =
        new LinkedList<>();

queue.offer("Java");
queue.offer("Spring");

System.out.println(queue.poll());

Output


Java

LinkedList as Stack


LinkedList<String> stack =
        new LinkedList<>();

stack.push("Java");
stack.push("Spring");

System.out.println(stack.pop());

Output


Spring

Time Complexity

Operation Complexity
Add First O(1)
Add Last O(1)
Remove First O(1)
Remove Last O(1)
Get By Index O(n)
Search O(n)

ArrayList vs LinkedList

Feature ArrayList LinkedList
Data Structure Dynamic Array Doubly Linked List
Random Access Fast Slow
Insertion Slower Faster
Deletion Slower Faster
Memory Usage Lower Higher

Real World Use Cases

  • Queue implementations
  • Browser navigation history
  • Undo and redo operations
  • Task scheduling systems
  • Music playlist navigation

Common Interview Questions

Which data structure does LinkedList use internally?

LinkedList uses a doubly linked list internally.

Why is LinkedList slower than ArrayList for retrieval?

LinkedList requires traversal from node to node because elements are not stored in contiguous memory.

When should LinkedList be preferred over ArrayList?

When insertions and deletions occur frequently, especially at the beginning or middle of the collection.

Does LinkedList allow null values?

Yes. LinkedList allows multiple null values.

Is LinkedList synchronized?

No. LinkedList is not thread-safe.

Best Practices

  • Use LinkedList when insertions and deletions are frequent.
  • Use ArrayList when random access is more important.
  • Avoid LinkedList for applications that perform frequent get(index) operations.
  • Consider LinkedList when implementing queues and stacks.

Frequently Asked Questions (FAQ)

Can LinkedList contain duplicate elements?

Yes. LinkedList allows duplicate elements.

Can LinkedList contain null values?

Yes. Multiple null values can be stored.

Why does LinkedList consume more memory?

Each node stores additional previous and next references along with the actual data.

What is the biggest advantage of LinkedList?

Efficient insertion and deletion operations.

Conclusion

LinkedList is an important collection implementation that uses a doubly linked list internally. It excels in insertion and deletion operations but sacrifices random access performance. Understanding its internal structure, node management, and performance characteristics helps developers choose the correct collection and answer advanced interview questions confidently.

Keywords

LinkedList Internal Working, LinkedList Interview Questions, How LinkedList Works Internally, LinkedList Java Tutorial, LinkedList Internal Architecture, LinkedList vs ArrayList, Doubly Linked List Java, Java Collections Framework, LinkedList Time Complexity, LinkedList Performance, LinkedList Queue Example, LinkedList Stack Example, Core Java Collections, Java Collections Interview Questions, LinkedList Examples

LinkedList Internal Working in Java with Examples LinkedList Internal Working in Java with Examples Reviewed by 13thGhost on 2:37 PM Rating: 5

TreeMap Internal Working in Java with Examples

2:22 PM

TreeMap is one of the most important Map implementations in Java Collections Framework. Unlike HashMap, which uses hashing internally, TreeMap stores data in a sorted order using a self-balancing Red-Black Tree.

TreeMap is frequently asked in Java interviews because understanding its internal implementation helps developers choose the correct collection based on requirements such as sorting, searching, and performance.

What is TreeMap?

TreeMap is a class that implements the NavigableMap interface and stores data in sorted key order. By default, sorting is performed according to the natural ordering of keys.


Map<Integer, String> map = new TreeMap<>();

map.put(103, "Spring");
map.put(101, "Java");
map.put(102, "Hibernate");

System.out.println(map);

Output


{101=Java, 102=Hibernate, 103=Spring}

Notice that the entries are automatically sorted by key.

Important Characteristics of TreeMap

  • Stores key-value pairs.
  • Maintains ascending sorted order of keys.
  • Does not allow null keys.
  • Allows multiple null values.
  • Uses Red-Black Tree internally.
  • Not synchronized.

Internal Structure of TreeMap

TreeMap internally uses a Red-Black Tree. A Red-Black Tree is a self-balancing binary search tree that ensures operations remain efficient even when large amounts of data are stored.

A simplified tree structure:


           50
         /    \
       25      75
      / \     / \
    10  35  60  90

Every insertion ensures the tree remains balanced.

Why Does TreeMap Use a Red-Black Tree?

If a normal binary search tree becomes unbalanced, search operations can become slow. The Red-Black Tree automatically balances itself to maintain efficient performance.


This guarantees that insertion, deletion, and searching operations remain fast.

How put() Works Internally


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

map.put(50, "A");
map.put(30, "B");
map.put(70, "C");

When put() is called:

  1. The root node is checked.
  2. The key is compared with existing keys.
  3. The correct position is located.
  4. A new node is inserted.
  5. The Red-Black Tree balancing algorithm runs.

How get() Works Internally


String value = map.get(30);

TreeMap performs:

  1. Start from root node.
  2. Compare required key with current node.
  3. Move left or right branch.
  4. Repeat until key is found.

Because the tree stays balanced, searching remains efficient.

Natural Sorting

TreeMap automatically sorts elements using natural ordering.


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

map.put(5, "Five");
map.put(1, "One");
map.put(3, "Three");

System.out.println(map);

Output


{1=One, 3=Three, 5=Five}

Custom Sorting Using Comparator

You can provide a custom Comparator to change the sorting behaviour.


TreeMap<Integer, String> map =
    new TreeMap<>(Collections.reverseOrder());

map.put(1, "Java");
map.put(2, "Spring");
map.put(3, "Kafka");

System.out.println(map);

Output


{3=Kafka, 2=Spring, 1=Java}

Null Key Behaviour

Unlike HashMap, TreeMap does not allow null keys.


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

map.put(null, "Java");

Output


Exception in thread "main"
java.lang.NullPointerException

TreeMap requires key comparisons and cannot compare null values.

TreeMap Methods Frequently Used

firstKey()


map.firstKey();

Returns the smallest key.

lastKey()


map.lastKey();

Returns the largest key.

higherKey()


map.higherKey(20);

Returns the next higher key.

lowerKey()


map.lowerKey(20);

Returns the previous lower key.

Internal Example


TreeMap<Integer, String> employees =
        new TreeMap<>();

employees.put(103, "Alex");
employees.put(101, "John");
employees.put(102, "David");

System.out.println(employees);

Output


{101=John, 102=David, 103=Alex}

Notice that entries are automatically sorted.

Time Complexity

Operation Complexity
put() O(log n)
get() O(log n)
remove() O(log n)

TreeMap vs HashMap

Feature HashMap TreeMap
Ordering No Sorted
Internal Structure Hash Table Red-Black Tree
Null Keys Allowed Not Allowed
Search Time O(1) O(log n)

Common Interview Questions

What data structure does TreeMap use internally?

TreeMap uses a Red-Black Tree internally.

Is TreeMap sorted?

Yes. TreeMap automatically stores entries in sorted order based on key values.

Can TreeMap contain null keys?

No. TreeMap does not allow null keys.

Can TreeMap contain null values?

Yes. Multiple null values are allowed.

When should TreeMap be used?

Use TreeMap when data must always remain sorted.

Frequently Asked Questions (FAQ)

Which is faster: HashMap or TreeMap?

HashMap is generally faster because it provides average O(1) lookup performance. TreeMap operations require O(log n) time.

What is the advantage of TreeMap?

Its biggest advantage is that it always maintains sorted data.

Can TreeMap sort custom objects?

Yes. Either implement Comparable or provide a Comparator.

Is TreeMap thread-safe?

No. TreeMap is not thread-safe.

Keywords

TreeMap Internal Working, TreeMap Interview Questions, Java TreeMap Tutorial, TreeMap Red Black Tree, TreeMap Example Java, TreeMap vs HashMap, TreeMap Time Complexity, Java Collections Framework, Sorted Map in Java, TreeMap Comparator Example, TreeMap Natural Ordering, TreeMap Internal Architecture, Java Collections Interview Questions, TreeMap Null Key, Core Java Collections

TreeMap Internal Working in Java with Examples TreeMap Internal Working in Java with Examples Reviewed by 13thGhost on 2:22 PM Rating: 5

HashSet Internal Working in Java with Examples

2:07 PM

HashSet is one of the most commonly used collection classes in Java. It is used whenever we need to store unique elements and want fast lookup performance. Although HashSet appears simple from the outside, its internal implementation is extremely interesting because it is actually backed by a HashMap.

In this article, we will explore how HashSet works internally, how it ensures uniqueness, how hashCode() and equals() play important roles, and common interview questions related to HashSet.

What is HashSet?

HashSet is a collection that implements the Set interface and does not allow duplicate elements. It is part of the Java Collections Framework.


Set<String> technologies = new HashSet<>();

technologies.add("Java");
technologies.add("Spring");
technologies.add("Java");

System.out.println(technologies);

Output


[Java, Spring]

Even though "Java" was added twice, HashSet stored it only once.

Important Characteristics of HashSet

  • Stores unique elements only.
  • Does not maintain insertion order.
  • Allows one null value.
  • Provides fast search operations.
  • Uses HashMap internally.
  • Not thread-safe.

How HashSet Works Internally

Many Java developers are surprised to learn that HashSet internally uses a HashMap. When you add an element to HashSet, it actually becomes a key inside an internal HashMap.

Simplified implementation:


public class HashSet<E> {

    private transient HashMap<E,Object> map;

    private static final Object PRESENT =
            new Object();

    public boolean add(E e) {
        return map.put(e, PRESENT) == null;
    }
}

Notice that:

  • HashSet element becomes HashMap key.
  • A dummy object is stored as value.
  • Uniqueness comes from HashMap key uniqueness.

What Happens When We Add an Element?


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

set.add("Java");

Internally:


map.put("Java", PRESENT);

HashMap stores "Java" as the key and a constant dummy object as the value.

How Duplicate Elements Are Prevented


set.add("Java");
set.add("Java");

HashMap does not allow duplicate keys. Since HashSet uses HashMap keys for storage, duplicate elements are automatically rejected.


The second insertion finds that the key already exists and therefore no new entry is added.

Role of hashCode()

When an object is added to HashSet, Java first calculates its hashCode().


String language = "Java";

int hash = language.hashCode();

System.out.println(hash);

The generated hash value helps determine the bucket location where the object should be stored.

Role of equals()

hashCode() identifies the bucket. equals() identifies the actual object inside the bucket.

Both methods work together to ensure uniqueness.

Example


public class Employee {

    private int id;

    public Employee(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object obj) {

        if(this == obj)
            return true;

        if(!(obj instanceof Employee))
            return false;

        Employee emp = (Employee)obj;

        return this.id == emp.id;
    }

    @Override
    public int hashCode() {
        return id;
    }
}

Without properly overriding equals() and hashCode(), duplicate objects may be added unexpectedly.

Example with Custom Objects


Set<Employee> employees =
        new HashSet<>();

employees.add(new Employee(1));
employees.add(new Employee(1));

System.out.println(employees.size());

Output


1

Since equals() and hashCode() are overridden correctly, HashSet identifies both objects as duplicates.

What Happens During Lookup?


set.contains("Java");

HashSet performs:

  1. Calculates hashCode().
  2. Locates bucket.
  3. Uses equals() to verify element.
  4. Returns result.

This is why contains() is usually very fast.

Can HashSet Store Null Values?

Yes. HashSet allows only one null value.


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

set.add(null);
set.add(null);

System.out.println(set.size());

Output


1

Iteration Order

HashSet does not guarantee insertion order.


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

set.add("C");
set.add("Java");
set.add("Spring");

System.out.println(set);

The output order may vary.

Time Complexity

Operation Average Complexity
Add O(1)
Contains O(1)
Remove O(1)

Worst-case performance can degrade when many collisions occur.

HashSet vs ArrayList

Feature HashSet ArrayList
Duplicates Not Allowed Allowed
Ordering No Yes
Search Performance Fast Slower

Common Interview Questions

Does HashSet allow duplicate values?

No. HashSet stores only unique elements.

How does HashSet ensure uniqueness?

It uses hashCode() and equals() methods together. Internally uniqueness is maintained by HashMap.

Can HashSet contain null?

Yes. Only one null value is allowed.

Is HashSet ordered?

No. HashSet does not maintain insertion order.

Which collection should be used when uniqueness is required?

HashSet is usually the preferred collection when duplicate values should not be stored.

Add links to the above articles once they are published on JavaCompass.

Frequently Asked Questions (FAQ)

Does HashSet use HashMap internally?

Yes. HashSet stores all elements as keys inside an internal HashMap.

Can HashSet have multiple null values?

No. Only one null value is allowed.

Which methods are important for HashSet?

hashCode() and equals() are crucial because they determine hashing and uniqueness.

Is HashSet thread-safe?

No. For concurrent environments, consider using ConcurrentHashMap-based solutions or synchronized collections.

Keywords

HashSet Internal Working, HashSet Interview Questions, HashSet Example Java, How HashSet Works Internally, HashSet Java Collections, HashSet vs ArrayList, HashSet hashCode equals, Java Collections Framework, HashSet Implementation, HashSet Performance, HashSet Duplicate Elements, HashSet Time Complexity, HashSet Internal Architecture, Java Set Interface, Core Java Collection Questions

HashSet Internal Working in Java with Examples HashSet Internal Working in Java with Examples Reviewed by 13thGhost on 2:07 PM Rating: 5

Difference Between HashMap and ConcurrentHashMap in Java with Examples

2:17 AM


HashMap and ConcurrentHashMap are two commonly used implementations of the Map interface in Java. While both store data as key-value pairs, they behave very differently in multi-threaded applications. Understanding these differences is essential for writing thread-safe and high-performance Java applications.





What is HashMap?

HashMap is a non-synchronized implementation of the Map interface. It provides excellent performance in single-threaded environments but is not safe for concurrent access by multiple threads.


Map<Integer, String> map = new HashMap<>();

map.put(1, "Java");
map.put(2, "Spring Boot");

System.out.println(map.get(1));

HashMap allows one null key and multiple null values.

What is ConcurrentHashMap?

ConcurrentHashMap is a thread-safe implementation of the Map interface introduced to support high-performance concurrent operations. Multiple threads can read and update the map simultaneously without causing data corruption.


Map<Integer, String> map = new ConcurrentHashMap<>();

map.put(1, "Java");
map.put(2, "Spring Boot");

System.out.println(map.get(1));

Why Do We Need ConcurrentHashMap?

Suppose multiple threads access a HashMap at the same time and one thread modifies the map while another thread reads it. This may result in inconsistent data and unpredictable behaviour.

ConcurrentHashMap was created to solve these problems while maintaining good performance.

HashMap Example in Multi-Threaded Environment


Map<Integer, String> map = new HashMap<>();

Runnable task = () -> {
    for(int i = 0; i < 1000; i++) {
        map.put(i, "Value " + i);
    }
};

new Thread(task).start();
new Thread(task).start();

The above code may produce inconsistent results because HashMap is not thread-safe.

ConcurrentHashMap Example


Map<Integer, String> map =
        new ConcurrentHashMap<>();

Runnable task = () -> {
    for(int i = 0; i < 1000; i++) {
        map.put(i, "Value " + i);
    }
};

new Thread(task).start();
new Thread(task).start();

ConcurrentHashMap handles concurrent operations safely without corrupting data.

Major Differences Between HashMap and ConcurrentHashMap

Feature HashMap ConcurrentHashMap
Thread Safe No Yes
Performance Fast in single thread Optimized for multiple threads
Null Key Allowed Not Allowed
Null Values Allowed Not Allowed
Synchronization Not Synchronized Internally Managed
Suitable For Single-threaded applications Multi-threaded applications



Why ConcurrentHashMap Does Not Allow Null Keys or Values

ConcurrentHashMap does not allow null keys or null values because it becomes difficult to determine whether a null result means that the key does not exist or that the value itself is null.


Map<Integer,String> map =
        new ConcurrentHashMap<>();

map.put(null, "Java");

Output


Exception in thread "main"
java.lang.NullPointerException

How ConcurrentHashMap Achieves Better Performance

In older Java versions, ConcurrentHashMap used segmented locking, allowing multiple threads to work on different segments simultaneously.

In modern Java versions, finer-grained locking and CAS (Compare-And-Swap) operations are used, which significantly improve performance.

Iterating Through ConcurrentHashMap

Unlike HashMap, ConcurrentHashMap supports safe iteration while updates are happening.


ConcurrentHashMap<Integer,String> map =
        new ConcurrentHashMap<>();

map.put(1, "Java");
map.put(2, "Spring");

for(Map.Entry<Integer,String> entry : map.entrySet()) {

    System.out.println(
        entry.getKey() + " : " +
        entry.getValue()
    );
}

When Should You Use HashMap?

  • Single-threaded applications
  • Desktop applications
  • Data processing programs
  • Situations where synchronization is unnecessary

When Should You Use ConcurrentHashMap?

  • Multi-threaded applications
  • Web applications
  • Microservices
  • Spring Boot applications
  • High-concurrency environments

Interview Questions

Can HashMap be used in multi-threaded applications?

HashMap can be used, but it is not thread-safe and may produce inconsistent results.

Does ConcurrentHashMap lock the entire map?

No. ConcurrentHashMap uses advanced concurrency techniques to minimize locking and improve performance.

Can ConcurrentHashMap store null values?

No. Both null keys and null values are prohibited.

Which is faster?

HashMap is generally faster in single-threaded environments. ConcurrentHashMap performs better when multiple threads need simultaneous access.

Best Practices

  • Use HashMap for single-threaded programs.
  • Use ConcurrentHashMap for web applications and APIs.
  • Avoid Hashtable in modern applications.
  • Never use HashMap for shared mutable data without synchronization.

Conclusion

Both HashMap and ConcurrentHashMap are powerful collection classes in Java. HashMap provides excellent performance for single-threaded applications, whereas ConcurrentHashMap is specifically designed for safe and efficient concurrent access. Choosing the correct implementation can improve both application performance and reliability.

Frequently Asked Questions (FAQ)

Is ConcurrentHashMap thread-safe?

Yes. ConcurrentHashMap is designed for concurrent access by multiple threads.

Can ConcurrentHashMap contain null values?

No. Null keys and null values are not permitted.

Can multiple threads read ConcurrentHashMap simultaneously?

Yes. Multiple threads can safely read data at the same time.

Which map implementation should be used in Spring Boot applications?

ConcurrentHashMap is typically preferred when shared data is accessed by multiple threads.

Related Articles

Keywords

HashMap vs ConcurrentHashMap, Difference Between HashMap and ConcurrentHashMap, ConcurrentHashMap Tutorial, Java Concurrent Collections, Java Multithreading Interview Questions, Thread Safe Collections in Java, ConcurrentHashMap Example, HashMap Thread Safety, ConcurrentHashMap Internal Working, Java Concurrency Tutorial, Java Collections Framework, Java Interview Questions, Thread Safe HashMap Alternative, ConcurrentHashMap in Spring Boot, Java Performance Optimization

Difference Between HashMap and ConcurrentHashMap in Java with Examples Difference Between HashMap and ConcurrentHashMap in Java with Examples Reviewed by 13thGhost on 2:17 AM Rating: 5

How HashMap Works Internally in Java with Examples

2:05 AM

HashMap is one of the most frequently used classes in Java and is a favourite topic in Java interviews. Almost every Java developer uses HashMap, but very few understand how it works internally. In this article, we will explore the internal working of HashMap, including buckets, hashCode(), collisions, linked lists, treeification, and performance optimizations.

What is HashMap?

HashMap is a part of the Java Collections Framework and is used to store data in key-value pairs. It allows one null key and multiple null values. HashMap does not maintain insertion order.


Map<Integer, String> employeeMap = new HashMap<>();

employeeMap.put(1, "John");
employeeMap.put(2, "David");
employeeMap.put(3, "Alex");

Important Characteristics of HashMap

  • Stores data as key-value pairs
  • Allows one null key
  • Allows multiple null values
  • Not synchronized
  • Provides nearly O(1) lookup performance
  • Uses hashing mechanism internally

Internal Structure of HashMap

Internally, HashMap stores data inside an array called buckets. Each bucket can contain multiple entries.


Bucket[0]
Bucket[1]
Bucket[2]
Bucket[3]
...
Bucket[n]

Whenever a key-value pair is inserted, HashMap calculates which bucket should contain the entry.

How put() Works Internally

When we add an element into HashMap:


map.put(101, "Java");

The following steps occur internally:

  1. HashMap calls hashCode() on the key.
  2. A hash value is generated.
  3. The bucket index is calculated.
  4. The key-value pair is stored in the bucket.
  5. If the bucket already contains data, collision handling occurs.

Example


Integer key = 101;

int hash = key.hashCode();

The generated hash helps HashMap identify the correct bucket location.

How get() Works Internally

Retrieving a value from HashMap is fast because Java calculates the bucket directly.


String course = map.get(101);

HashMap performs these operations:

  1. Calculate hashCode() of the key.
  2. Identify bucket index.
  3. Search inside the bucket.
  4. Compare keys using equals().
  5. Return matching value.

What is Collision in HashMap?

A collision occurs when two different keys generate the same bucket index.


map.put(1, "Java");
map.put(17, "Spring");

Both keys may point to the same bucket. In such cases HashMap stores multiple entries inside that bucket.

Collision Handling Before Java 8

Before Java 8, collisions were handled using Linked Lists.


Bucket 15

Key1 -> Key2 -> Key3 -> Key4

Searching becomes slower as the linked list grows.

Collision Handling in Java 8 and Later

Java 8 introduced Treeification. When the number of entries in a bucket exceeds a threshold, the linked list converts into a Red-Black Tree.


Bucket 15

         7
       /   \
      3     12
     / \   / \
    1  5 10 15

This improves lookup performance significantly.

Performance Comparison

Structure Search Complexity
Linked List O(n)
Red Black Tree O(log n)

Why equals() and hashCode() Are Important

HashMap relies heavily on both hashCode() and equals().

hashCode() identifies the bucket and equals() identifies the exact object within that bucket.

Example


public class Employee {

    private int id;

    public Employee(int id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        return id;
    }

    @Override
    public boolean equals(Object obj) {

        if(this == obj)
            return true;

        if(obj == null || getClass() != obj.getClass())
            return false;

        Employee emp = (Employee)obj;

        return id == emp.id;
    }
}

Overriding both methods correctly ensures HashMap behaves properly.

Initial Capacity and Load Factor

HashMap uses two important parameters:

  • Initial Capacity = 16
  • Load Factor = 0.75

When capacity reaches 75%, HashMap automatically resizes.


Map<Integer,String> map =
new HashMap<>(32,0.75f);

Time Complexity of HashMap Operations

Operation Complexity
put() O(1)
get() O(1)
remove() O(1)
Worst Case O(log n)

Real-World Example


Map<Integer,String> employees =
new HashMap<>();

employees.put(101,"John");
employees.put(102,"David");
employees.put(103,"Alex");

System.out.println(employees.get(102));

Output


David

Common HashMap Interview Questions

  1. How does HashMap work internally?
  2. What causes a collision?
  3. What is Treeification?
  4. Difference between HashMap and Hashtable?
  5. Why override equals() and hashCode()?
  6. What is Load Factor?
  7. Can HashMap have null keys?
  8. What is the default capacity of HashMap?

Conclusion

HashMap is one of the most important data structures in Java. It provides near constant-time performance using hashing techniques. Understanding buckets, hashCode(), equals(), collisions, linked lists, and red-black trees will help developers write efficient applications and perform well in Java interviews.

Related Articles

Keywords

HashMap Internal Working, How HashMap Works in Java, HashMap Interview Questions, Java Collections Framework, HashMap Collision Handling, HashMap Java 8, HashMap Buckets, hashCode and equals in Java, Java HashMap Examples, HashMap Performance, Treeification in HashMap, Java Collection Interview Questions, HashMap Time Complexity, Java Core Concepts, Java Programming Tutorial

How HashMap Works Internally in Java with Examples How HashMap Works Internally in Java with Examples Reviewed by 13thGhost on 2:05 AM Rating: 5

What is the difference between 'final' method, class and variable in Java? Explained with example.

9:38 PM

 Java's final keyword is a modifier that can be applied to classes, methods, and variables. When applied to a class, it means that the class cannot be subclassed. When applied to a method, it means that the method cannot be overridden in a subclass. When applied to a variable, it means that the variable's value cannot be changed once it is assigned.


Using the final keyword can be beneficial in certain situations, as it can make your code more robust and less prone to errors. In this blog post, we'll take a look at how to use the final keyword in Java and see some examples of its use.


Classes

When applied to a class, final means that the class cannot be subclassed. This can be useful if you want to ensure that a class is always used in the same way and that its behavior cannot be changed.



final class MyClass {
    // code here
}

class Subclass extends MyClass { // Compile-time error
    // code here
}


Methods

When applied to a method, final means that the method cannot be overridden in a subclass. This can be useful if you want to ensure that a method always behaves in the same way, regardless of the subclass that is calling it.



class MyClass {
    final void myMethod() {
        // code here
    }
}

class Subclass extends MyClass {
    void myMethod() { // Compile-time error
        // code here
    }
}

Variables

When applied to a variable, final means that the variable's value cannot be changed once it is assigned. This can be useful if you want to ensure that a variable always has the same value, regardless of the code that is executed.



final int myVariable = 5;
myVariable = 10; // Compile-time error

In addition to the above examples, final variables can also be used for constants in a class



class MyClass {
    static final int MAX_COUNT = 100;
}

Final keyword is a powerful tool that can be used to make your code more robust and less prone to errors. It can be applied to classes, methods, and variables to ensure that their behavior cannot be changed. By using final keyword, you can ensure that the classes, methods, and variables always behave in the same way, regardless of the code that is executed.

What is the difference between 'final' method, class and variable in Java? Explained with example. What is the difference between 'final' method, class and variable in Java? Explained with example. Reviewed by 13thGhost on 9:38 PM Rating: 5

Fail Fast Vs Fail Safe Iterator In Java

1:59 AM

Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification  of the collection.

 Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure.


Fail Fast IteratorFail Safe Iterator
Throws ConcurrentModification Exception.Does not throws ConcurrentModification Exception.
Does not clone object .Clones objects.
No memory Overhead occurs.Memory Overhead occurs.
Examples:HashMap,Vector ,ArrayList, HashSet.Examples:CopyOnWriteArrayList,
ConcurrentHashMap

Concurrent Modification

When one or more thread is iterating over a collection, and in between if one thread changes the structure of the collection (either adding a element or by deleting a element or by updating a value  in the collection) is known as Concurrent Modification.

Fail-fast Iterator Example:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class FailFastExample
{
    
    
    public static void main(String[] args)
    {
        Map mapExample = new HashMap();
        mapExample.put("key1", "value1");
        mapExample.put("key2", "value2");
        mapExample.put("key3","value3");
        
        Iterator iterator = mapExample.keySet().iterator();
        
        while (iterator.hasNext())
        {
            System.out.println(mapExample.get(iterator.next()));
            mapExample.put("key4", "value4");
        }
        
    }
    
}


Output:
value1 Exception in thread "main" java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextEntry(Unknown Source) at java.util.HashMap$KeyIterator.next(Unknown Source) at FailFastExample.main(FailFastExample.java:20)

Fail-Safe Iterator Example:
import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;


public class FailSafeExample
{
    
    
    public static void main(String[] args)
    {
        ConcurrentHashMap mapExample = 
                               new ConcurrentHashMap();
        mapExample.put("key1", "value1");
        mapExample.put("key2", "value2");
        mapExample.put("key3","value3");
        
        Iterator iterator = mapExample.keySet().iterator();
        
        while (iterator.hasNext())
        {
            System.out.println(mapExample.get(iterator.next()));
            mapExample.put("key4", "value4");
        }
        
    }
    
}
Output:
value1
value2
value3
value4

Fail Fast Vs Fail Safe Iterator In Java Fail Fast Vs Fail Safe Iterator In Java Reviewed by 13thGhost on 1:59 AM Rating: 5

Recommended Posts

Powered by Blogger.