Sitemap
Quipoin

Quipoin

Set Interface in Java

2 min readNov 22, 2025

--

The Set interface is a part of the Java Collection Framework and is used to store a collection of unique elements.
Unlike List, a Set does not allow duplicate values and doesn’t maintain insertion order (except specific implementations).

Block Diagram of Set Interface

<<Collection>>
▲
|
<<Set Interface>>
/ | \
/ | \
<HashSet> <LinkedHashSet> <TreeSet>

▶ << >> : Interface
▶ < > : Class
▶ ----> : Represents Implementation

Implementation Classes of Set Interface

1 HashSet

Uses HashTable for internal storage.

Does not maintain insertion order.

Provides constant-time performance for add, remove & search.

Best for fast operations where ordering doesn’t matter.

Example

import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("Java"); // Duplicate ignored
System.out.println(set);
}
}

Output
[Java, Python] (Order may vary)

2 LinkedHashSet

Maintains insertion order.

Slightly slower than HashSet due to ordering.

Get Quipoin’s stories in your inbox

Join Medium for free to get updates from this writer.

Good when you want uniqueness + order.

Example

import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add(30);
set.add(10);
set.add(20);
System.out.println(set);
}
}

Output
[30, 10, 20]

3 TreeSet

Stores elements in sorted order (ascending by default).

Implements NavigableSet, supports range-based operations.

Slower than HashSet & LinkedHashSet due to sorting.

Example

import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
set.add(50);
set.add(10);
set.add(30);
System.out.println(set);
}
}

Output
[10, 30, 50]

Advantages of Set

✔ Stores unique elements
✔ Better performance than List for search operations
✔ Useful for removing duplicates

Limitations

✘ No indexing (cannot access using index)
✘ Order not guaranteed in some implementations

For More Learning:

Interview Practice: https://www.quipoin.com/interview/java/set-interface

Video Tutorial: https://youtu.be/r1J4p8d-MP0?si=svU6rn4KWD5L0P2z

--

--