Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Java’s Set interface represents a collection of unique values, but it does not prescribe how those values are stored or encountered. Use HashSet when order does not matter, LinkedHashSet for insertion order, TreeSet for sorted and navigable values, and EnumSet for values of one enum type. For a fixed or defensive unmodifiable set, use Set.of or Set.copyOf.

What a Java Set guarantees

Oracle’s Java SE 26 API defines a set as “A collection that contains no duplicate elements.” The Set interface determines duplicates using equals: adding an element equal to one already present leaves the set unchanged and returns false. A set’s own equality is based on having the same size and containing the same elements, regardless of iteration order or implementation class.

Set is an interface, not a class you instantiate directly. Declare a variable using the interface and construct an implementation that matches the behavior you need:

Set<String> names = new HashSet<>();
Set<String> insertionOrdered = new LinkedHashSet<>();
Set<String> sorted = new TreeSet<>();

The interface contract allows at most one null, but particular implementations can be stricter. Likewise, neither ordering nor thread safety is guaranteed by the interface itself.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose an implementation by behavior

Need Choice Behavior and caveats
General membership; order does not matter HashSet No iteration-order guarantee; permits null; unsynchronized. Basic operations are described as constant time assuming hashes are well dispersed.
Insertion encounter order LinkedHashSet Maintains insertion order; adding an equal value again does not move it. In Java SE 26 it implements SequencedSet.
Sorted iteration, ranges, or navigation TreeSet Uses natural ordering or a supplied comparator; basic add, remove, and contains operations are logarithmic. Ordering consistency with equals matters.
Values from one enum type EnumSet Compact bit-vector representation; iteration follows enum declaration order; rejects null.
Fixed set or unmodifiable copy Set.of / Set.copyOf Unmodifiable and null-free; factory iteration order is unspecified. Set.of rejects duplicate arguments.

These are API complexity descriptions, not application benchmarks. Actual performance depends on the data, hash distribution, comparison cost, allocations, and workload; the API specifications do not provide application-specific timings.

HashSet: membership without an order promise

HashSet is the usual general-purpose choice when you need to test membership or prevent duplicates and do not care about traversal order. Oracle documents constant-time basic add, remove, contains, and size operations when the hash function disperses elements properly. Its iteration cost depends on both the number of elements and the capacity of the backing hash table, so an oversized set can make traversal more expensive than its element count alone suggests.

It permits one null and is not synchronized. If multiple threads access it and at least one modifies it, provide external synchronization or use a concurrent collection designed for the workload.

LinkedHashSet: preserve insertion order

Choose LinkedHashSet when callers should encounter values in the order they were first added. Adding a value that compares equal under equals does not create a duplicate or change that value’s position. Its Java SE 26 API implements SequencedSet; that specific interface should not be assumed on older Java releases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

TreeSet: sorted and navigable values

TreeSet maintains values in natural order or according to a supplied Comparator. That ordering enables sorted traversal and navigable or range-based operations. Oracle documents logarithmic basic add, remove, and contains operations in the TreeSet API.

Unlike HashSet, TreeSet uses comparison results to determine whether two entries occupy the same position for set purposes. If the comparator reports two objects as equivalent while their equals methods say they differ, the tree can operate, but it does not satisfy the general Set contract. Use a natural ordering or comparator consistent with equals when you need ordinary set semantics. Ordering constraints also affect whether null is accepted.

TreeSet is not synchronized. Concurrent access that includes modification requires external synchronization or a collection intended for concurrent use.

EnumSet: the focused choice for enum values

When every member comes from one enum type, EnumSet is the specialized set implementation. Its compact bit-vector representation is designed for enum values, and iteration follows the constants’ declaration order. It rejects null. See Oracle’s EnumSet API for its contract and operations. It is not synchronized; concurrent modifications require external synchronization.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set.of and Set.copyOf: unmodifiable factory results

Use Set.of for a small fixed set of values or Set.copyOf to create an unmodifiable set from another collection. Both reject null, and their iteration order is unspecified and may change. Set.of throws IllegalArgumentException if its arguments contain duplicates. These behaviors are documented in Oracle’s Set API.

“Unmodifiable” applies to operations on the collection; it does not make its elements immutable. If a member object is mutable, its state can still change after it is placed in the set.

Keep equality stable while an element is stored

The Set contract warns that behavior is unspecified if an element changes while it is in a set in a way that affects equality comparisons. For hash-based sets, changing fields involved in equals or hashCode can make an element difficult to find or remove. Prefer immutable keys, or avoid changing equality-relevant state until the element has been removed and can be added again.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use bulk operations for set relationships

Bulk operations mutate the receiving set when that implementation supports the operation. With another set, their usual mathematical interpretations are:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • addAll(other): union; adds the other set’s elements to the receiver.
  • retainAll(other): intersection; keeps only receiver elements also present in the other set.
  • removeAll(other): asymmetric difference; removes from the receiver elements found in the other set.

These methods do not automatically create and return a new set. The Set API defines their behavior; use a copy first if the original collection must remain unchanged.

Are Java Set implementations thread-safe?

No general thread-safety guarantee comes from the Set interface. HashSet, TreeSet, and EnumSet require external synchronization when concurrent access includes modification. For concurrent updates, choose a concurrent collection suited to the required ordering and operations rather than treating an ordinary set as thread-safe. Oracle’s Collections API documents collection utilities, including synchronization wrappers.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.