Java · Collections · Topic 3
Set Interface
Understand unique-element collections through HashSet, LinkedHashSet, SortedSet, NavigableSet, TreeSet, and mathematical set operations.
Step 1 of 11
3.1 Introduction to Set
Define Set behavior and explain what happens when a duplicate value is added.
Set extends Collection and represents a group that does not allow duplicate elements. The generic type E identifies the stored element type.
public interface Set<E> extends Collection<E>Main Set characteristics
- Duplicate elements are not allowed
- Index-based access is not supported
- At most one null may be stored, depending on the implementation
- Element order depends on the implementation
- Useful whenever uniqueness is required
import java.util.HashSet;
import java.util.Set;
public class SetIntroductionDemo {
public static void main(String[] args) {
Set<String> names = new HashSet<>();
names.add("Amit");
names.add("Neha");
names.add("Amit");
System.out.println(names);
}
}[Amit, Neha]Check your understanding: What does add() do when an equal element already exists?
It leaves the set unchanged and returns false.
Step 2 of 11
3.2 Set hierarchy
Read the main Set relationships and match each implementation to its ordering behavior.
Set extends Collection. HashSet is the base hashing implementation, LinkedHashSet extends HashSet, SortedSet extends Set, NavigableSet extends SortedSet, and TreeSet implements NavigableSet.
| Parent | Relationship | Child |
|---|---|---|
| Collection<E> | extended by | Set<E> |
| Set<E> | implemented by | HashSet<E> |
| HashSet<E> | extended by | LinkedHashSet<E> |
| Set<E> | extended by | SortedSet<E> |
| SortedSet<E> | extended by | NavigableSet<E> |
| NavigableSet<E> | implemented by | TreeSet<E> |
| Implementation | Ordering |
|---|---|
| HashSet | No guaranteed order |
| LinkedHashSet | Insertion order |
| TreeSet | Sorted order |
Check your understanding: Which interface adds navigation methods such as lower() and ceiling()?
NavigableSet.
Step 3 of 11
3.3 Important Set methods
Use inherited Collection methods and interpret the boolean result of add().
| Method | Description |
|---|---|
| add(element) | Adds an element |
| addAll(collection) | Adds all elements of another collection |
| remove(element) | Removes an element |
| removeAll(collection) | Removes matching elements |
| retainAll(collection) | Retains common elements |
| contains(element) | Checks whether an element exists |
| containsAll(collection) | Checks whether all elements exist |
| size() | Returns the element count |
| isEmpty() | Checks whether the set is empty |
| clear() | Removes all elements |
| iterator() | Returns an iterator |
import java.util.HashSet;
import java.util.Set;
public class SetAddResultDemo {
public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
System.out.println(numbers.add(10));
System.out.println(numbers.add(20));
System.out.println(numbers.add(10));
}
}true
true
falseCheck your understanding: What does numbers.add(10) return the second time it is called?
false, because 10 is already present.
Step 4 of 11
3.4 HashSet
Explain hashing, duplicate detection, order guarantees, performance, and suitable use cases.
HashSet characteristics
- Rejects duplicates
- Does not maintain insertion order
- Does not sort elements
- Allows at most one null
- Provides fast average insertion, deletion, and search
- Is not synchronized
- Uses hashCode() and equals() for duplicate detection
import java.util.HashSet;
import java.util.Set;
public class HashSetDemo {
public static void main(String[] args) {
Set<String> subjects = new HashSet<>();
subjects.add("Java");
subjects.add("Python");
subjects.add("Database");
subjects.add("Java");
subjects.add(null);
System.out.println(subjects);
System.out.println("Total subjects: " + subjects.size());
System.out.println("Contains Java: " + subjects.contains("Java"));
subjects.remove("Python");
System.out.println("After removal: " + subjects);
}
}[null, Java, Database, Python]
Total subjects: 4
Contains Java: true
After removal: [null, Java, Database]How duplicate detection works
When an element is added, Java calculates its hash code to select a storage location. If a candidate has the same hash, equals() determines whether it is a duplicate. Predefined classes already implement these methods; user-defined value classes should override both for logical equality.
| Operation | Complexity |
|---|---|
| add() | O(1) |
| remove() | O(1) |
| contains() | O(1) |
| Traversal | O(n) |
Check your understanding: Which two methods cooperate to detect logical duplicates in HashSet?
hashCode() selects a hash location and equals() confirms equality when needed.
Step 5 of 11
3.5 LinkedHashSet
Use LinkedHashSet when unique elements must retain their insertion order.
LinkedHashSet characteristics
- Does not allow duplicates
- Maintains insertion order
- Allows at most one null
- Uses hashing plus a linked structure
- Is slightly slower than HashSet
- Is not synchronized
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetDemo {
public static void main(String[] args) {
Set<String> cities = new LinkedHashSet<>();
cities.add("Anand");
cities.add("Vadodara");
cities.add("Ahmedabad");
cities.add("Anand");
cities.add("Surat");
System.out.println(cities);
}
}[Anand, Vadodara, Ahmedabad, Surat]Check your understanding: Does LinkedHashSet sort its elements?
No. It preserves insertion order but does not sort.
Step 6 of 11
3.6 SortedSet
Use range-view and endpoint methods supplied by the SortedSet interface.
SortedSet is a child interface of Set that maintains unique elements in sorted order. TreeSet is its common implementation.
SortedSet<Integer> numbers = new TreeSet<>();| Method | Description |
|---|---|
| first() | Returns the first element |
| last() | Returns the last element |
| headSet(element) | Returns elements smaller than the element |
| tailSet(element) | Returns elements greater than or equal to the element |
| subSet(from, to) | Returns elements within a range |
| comparator() | Returns the comparator used for sorting |
Check your understanding: Which method returns elements smaller than a boundary value?
headSet(boundary).
Step 7 of 11
3.7 NavigableSet
Select the correct nearest-match method and use safe endpoint removal.
NavigableSet extends SortedSet and finds the closest matching elements around a search value.
| Method | Meaning |
|---|---|
| lower(x) | Greatest element strictly smaller than x |
| floor(x) | Greatest element smaller than or equal to x |
| ceiling(x) | Smallest element greater than or equal to x |
| higher(x) | Smallest element strictly greater than x |
| pollFirst() | Retrieves and removes the first element |
| pollLast() | Retrieves and removes the last element |
| descendingSet() | Returns elements in reverse order |
Check your understanding: How do floor(40) and lower(40) differ when 40 exists?
floor(40) may return 40; lower(40) must return a value strictly smaller than 40.
Step 8 of 11
3.8 TreeSet
Trace TreeSet ordering, navigation, comparator use, and logarithmic operations.
TreeSet characteristics
- Rejects duplicates
- Stores elements in sorted order
- Does not preserve insertion order
- Normally does not allow null
- Supports range and nearest-value methods
- Requires mutually comparable elements
- Is not synchronized
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(50);
numbers.add(10);
numbers.add(40);
numbers.add(20);
numbers.add(10);
System.out.println(numbers);
System.out.println("First: " + numbers.first());
System.out.println("Last: " + numbers.last());
System.out.println("Lower than 40: " + numbers.lower(40));
System.out.println("Floor of 40: " + numbers.floor(40));
System.out.println("Higher than 40: " + numbers.higher(40));
System.out.println("Ceiling of 35: " + numbers.ceiling(35));
}
}[10, 20, 40, 50]
First: 10
Last: 50
Lower than 40: 20
Floor of 40: 40
Higher than 40: 50
Ceiling of 35: 40TreeSet<String> names = new TreeSet<>();
names.add("Raj");
names.add("Amit");
names.add("Neha");
// [Amit, Neha, Raj]
TreeSet<Integer> reverse = new TreeSet<>(Comparator.reverseOrder());
reverse.add(10);
reverse.add(30);
reverse.add(20);
// [30, 20, 10]| Operation | Complexity |
|---|---|
| add() | O(log n) |
| remove() | O(log n) |
| contains() | O(log n) |
| first() and last() | O(log n) |
Check your understanding: Why must TreeSet elements be mutually comparable?
TreeSet must compare elements to place them in sorted order.
Step 9 of 11
3.9 Set operations
Perform union, intersection, and difference without changing the original sets.
Set<Integer> setA = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> setB = new HashSet<>(Arrays.asList(3, 4, 5, 6));import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class SetOperationsDemo {
public static void main(String[] args) {
Set<Integer> setA = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> setB = new HashSet<>(Arrays.asList(3, 4, 5, 6));
Set<Integer> union = new HashSet<>(setA);
union.addAll(setB);
Set<Integer> intersection = new HashSet<>(setA);
intersection.retainAll(setB);
Set<Integer> difference = new HashSet<>(setA);
difference.removeAll(setB);
System.out.println("Union: " + union);
System.out.println("Intersection: " + intersection);
System.out.println("Difference: " + difference);
}
}Union: [1, 2, 3, 4, 5, 6]
Intersection: [3, 4]
Difference: [1, 2]| Operation | Set method |
|---|---|
| Union | addAll() |
| Intersection | retainAll() |
| Difference | removeAll() |
Check your understanding: Which method produces the intersection when applied to a copy of setA?
retainAll(setB).
Step 10 of 11
3.10 Comparison of Set Implementations
Choose HashSet, LinkedHashSet, or TreeSet from ordering, speed, null, and range requirements.
| Feature | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
| Duplicates | Not allowed | Not allowed | Not allowed |
| Element order | No guaranteed order | Insertion order | Sorted order |
| null | One allowed | One allowed | Normally not allowed |
| Basic speed | Fastest on average | Slightly slower | Slower |
| Internal structure | Hash table | Hash table and linked list | Balanced tree |
| Range operations | No | No | Yes |
| Best use | Fast unique storage | Unique ordered storage | Unique sorted storage |
Check your understanding: Which implementation supports range operations such as subSet()?
TreeSet.
Step 11 of 11
3.11 List versus Set
Distinguish List and Set by duplication, indexing, order, and typical implementations.
| List | Set |
|---|---|
| Allows duplicates | Does not allow duplicates |
| Maintains an element sequence | Order depends on implementation |
| Supports indexes | Does not support indexes |
| Provides get(index) | Does not provide get(index) |
| May allow multiple null values | Usually allows at most one null |
| Examples: ArrayList, LinkedList | Examples: HashSet, TreeSet |
Check your understanding: Which interface provides get(index)?
List; Set does not support index-based access.