HashSet
LinkedHashSet
Java Collections
Data Structures
Java Programming

HashSet vs LinkedHashSet

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In Java, the HashSet and LinkedHashSet are part of the Java Collections Framework, specifically implementing the Set interface. Both classes provide a set-based collection to store unique elements. However, they exhibit different behaviors concerning element ordering, performance, and memory usage. This article explores these differences in depth, alongside providing examples that illustrate their respective use cases.

Overview of HashSet

HashSet is one of the most commonly used implementations of the Set interface. Under the hood, it utilizes a hash table to store elements. Here's a breakdown of its characteristics:

  • Order: HashSet does not maintain any order of its elements. Internally, it may change the order based on hash codes of the objects.
  • Performance: It has an average time complexity of O(1)O(1) for basic operations like add, remove, and contains thanks to its hashing mechanism.
  • Null Elements: HashSet allows the inclusion of null elements. However, there should not be multiple null entries since a set inherently maintains uniqueness.
  • Synchronization: It is non-synchronized, implying it is not thread-safe. To use it in a concurrent environment, external synchronization is required.

Example Usage

java
1import java.util.HashSet;
2import java.util.Set;
3
4public class HashSetExample {
5    public static void main(String[] args) {
6        Set<String> hashSet = new HashSet<>();
7        hashSet.add("Apple");
8        hashSet.add("Banana");
9        hashSet.add("Cherry");
10        hashSet.add("Apple"); // Duplicate, won't be added
11
12        // Output: [Banana, Apple, Cherry] (unordered)
13        System.out.println(hashSet);
14    }
15}

Overview of LinkedHashSet

LinkedHashSet extends HashSet and adds an extra layer of functionality: predictable iteration order, which is the order in which elements were inserted. Here are its main features:

  • Order: Preserves the insertion order. As a result, retrieval time complexity is higher than the direct hash-based storage in HashSet.
  • Performance: Although its basic operations still exhibit average time complexities of O(1)O(1), the overhead due to maintaining the linked list for order can make operations slightly slower than HashSet.
  • Null Elements: Like HashSet, LinkedHashSet also allows null.
  • Synchronization: Similar to HashSet, it is non-synchronized and requires explicit synchronization for concurrent use.

Example Usage

java
1import java.util.LinkedHashSet;
2import java.util.Set;
3
4public class LinkedHashSetExample {
5    public static void main(String[] args) {
6        Set<String> linkedHashSet = new LinkedHashSet<>();
7        linkedHashSet.add("Apple");
8        linkedHashSet.add("Banana");
9        linkedHashSet.add("Cherry");
10        linkedHashSet.add("Apple"); // Duplicate, won't be added
11
12        // Output: [Apple, Banana, Cherry] (ordered)
13        System.out.println(linkedHashSet);
14    }
15}

Key Differences and Use Cases

FeatureHashSetLinkedHashSet
OrderingNo guarantee of orderMaintains insertion order
PerformanceSlightly faster due to simpler data structure (hash table only)Slightly slower due to additional linked list overhead
Use CasesSituations where order doesn't matter and fastest performance is desiredSituations where elements must be iterated in the same order they were added

Memory Considerations

LinkedHashSet incurs additional memory overhead compared to HashSet due to the maintenance of a linked list along with the hash table. This overhead is worthwhile for problems where the specific order of elements is significant once they're added to the set.

When to Use Which?

  • Choose HashSet when order does not matter: If you have a scenario where element order is inconsequential, opt for HashSet for its slightly better performance and lower memory usage.
  • Choose LinkedHashSet for predictable iteration order: If iteration order is significant in your application logic, LinkedHashSet is the preferred choice despite its slight overhead.

Conclusion

Both HashSet and LinkedHashSet are potent implementations of the Set interface, each catering to specific needs based on order requirements and performance considerations. By understanding their differences, developers can make informed decisions to optimize the performance and predictability of their Java applications.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.