Dr. Vatsal Shah
Subject Material

Java · Collections · Topic 3

Set Interface

Understand unique-element collections through HashSet, LinkedHashSet, SortedSet, NavigableSet, TreeSet, and mathematical set operations.

Topic progress · 1 of 11 sections

Step 1 of 11

3.1 Introduction to Set

Learning objective

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.

Set interface relationship
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
SetIntroductionDemo.java
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);
    }
}
Possible output
[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

Learning objective

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.

Set hierarchy relationships
ParentRelationshipChild
Collection<E>extended bySet<E>
Set<E>implemented byHashSet<E>
HashSet<E>extended byLinkedHashSet<E>
Set<E>extended bySortedSet<E>
SortedSet<E>extended byNavigableSet<E>
NavigableSet<E>implemented byTreeSet<E>
Main Set implementations
ImplementationOrdering
HashSetNo guaranteed order
LinkedHashSetInsertion order
TreeSetSorted order
Check your understanding: Which interface adds navigation methods such as lower() and ceiling()?

NavigableSet.

Step 3 of 11

3.3 Important Set methods

Learning objective

Use inherited Collection methods and interpret the boolean result of add().

Important Set methods
MethodDescription
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
SetAddResultDemo.java
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));
    }
}
Output
true
true
false
Check 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

Learning objective

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
HashSetDemo.java
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);
    }
}
Possible output
[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.

Average HashSet complexity
OperationComplexity
add()O(1)
remove()O(1)
contains()O(1)
TraversalO(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

Learning objective

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
LinkedHashSetDemo.java
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);
    }
}
Output
[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

Learning objective

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.

Creating a SortedSet
SortedSet<Integer> numbers = new TreeSet<>();
SortedSet methods
MethodDescription
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

Learning objective

Select the correct nearest-match method and use safe endpoint removal.

NavigableSet extends SortedSet and finds the closest matching elements around a search value.

NavigableSet methods
MethodMeaning
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

Learning objective

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
TreeSetDemo.java
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));
    }
}
Output
[10, 20, 40, 50]
First: 10
Last: 50
Lower than 40: 20
Floor of 40: 40
Higher than 40: 50
Ceiling of 35: 40
Natural and reverse ordering
TreeSet<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]
TreeSet complexity
OperationComplexity
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

Learning objective

Perform union, intersection, and difference without changing the original sets.

Starting sets
Set<Integer> setA = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> setB = new HashSet<>(Arrays.asList(3, 4, 5, 6));
SetOperationsDemo.java
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);
    }
}
Results
Union: [1, 2, 3, 4, 5, 6]
Intersection: [3, 4]
Difference: [1, 2]
Mathematical operation mapping
OperationSet method
UnionaddAll()
IntersectionretainAll()
DifferenceremoveAll()
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

Learning objective

Choose HashSet, LinkedHashSet, or TreeSet from ordering, speed, null, and range requirements.

Set implementation comparison
FeatureHashSetLinkedHashSetTreeSet
DuplicatesNot allowedNot allowedNot allowed
Element orderNo guaranteed orderInsertion orderSorted order
nullOne allowedOne allowedNormally not allowed
Basic speedFastest on averageSlightly slowerSlower
Internal structureHash tableHash table and linked listBalanced tree
Range operationsNoNoYes
Best useFast unique storageUnique ordered storageUnique sorted storage
Check your understanding: Which implementation supports range operations such as subSet()?

TreeSet.

Step 11 of 11

3.11 List versus Set

Learning objective

Distinguish List and Set by duplication, indexing, order, and typical implementations.

List and Set comparison
ListSet
Allows duplicatesDoes not allow duplicates
Maintains an element sequenceOrder depends on implementation
Supports indexesDoes not support indexes
Provides get(index)Does not provide get(index)
May allow multiple null valuesUsually allows at most one null
Examples: ArrayList, LinkedListExamples: HashSet, TreeSet
Check your understanding: Which interface provides get(index)?

List; Set does not support index-based access.