Java HashSet and TreeSet: Hash Tables, Hash Codes and Sorted Sets
How Java's HashSet and TreeSet work: hash codes, buckets, collisions, load factor and rehashing, HashSet.newHashSet, the danger of mutating set elements, red-black tree sorted sets, comparators that disagree with equals, and NavigableSet methods like floor, ceiling and headSet.
kvi5hnuCode Sprout team member12 min readOn this page
Lists keep elements in the order you choose. The price is that finding an element means checking them one by one. If you don't care about position and mostly ask "is this element in here?", there are much faster structures. This article covers the two main set implementations. HashSet is built on a hash table and finds elements in roughly constant time. TreeSet is built on a balanced tree and keeps its elements sorted.
Hash tables in one picture
A hash table computes an integer, the hash code, for every object, and uses it to decide where the object lives. In Java the hash code comes from the object's hashCode method. For a string, it is derived from the characters:
| String | hashCode() |
|---|---|
"Lee" | 76268 |
"lee" | 107020 |
"eel" | 100300 |
"Aa" | 2112 |
"BB" | 2112 |
Two properties matter. A hash code can be computed quickly, and it depends only on the object itself, not on whatever else is in the table. Different objects usually get different codes, but not always: "Aa" and "BB" share 2112.
For your own classes, hashCode must be compatible with equals: if a.equals(b), then a.hashCode() == b.hashCode(). The earlier articles on the equals method and hashCode show how to write both. Records, enums and String already get it right.

Java implements a hash table as an array of buckets. Each bucket holds the entries whose hash codes map to it. To find an object's bucket, the table reduces the hash code to an index. Conceptually that is hash % bucketCount: with 128 buckets, hash code 76268 goes to bucket 108. Because Java always uses a power-of-two bucket count, the JDK computes the same thing faster as hash & (n − 1), after first mixing the high bits into the low ones so that codes differing only in their upper bits still spread out.
When the bucket is empty, insertion is immediate. When it already holds entries, that is a hash collision, and the table calls equals on each entry in the bucket to see whether the object is already present. With well-spread hash codes and enough buckets, a bucket holds only a few entries, so lookup, insertion and removal are all O(1) on average.
Load factor and rehashing
A table that gets too full slows down. The load factor sets the limit. With the default of 0.75, a table whose size exceeds 75% of its bucket count is rehashed: a table with twice as many buckets is allocated, every element is reinserted, and the old table is discarded. The default bucket count is 16, so the first rehash happens when the 13th element arrives. Any initial capacity you supply is rounded up to a power of two.
Leaving the load factor at 0.75 is the right choice almost always. If you know how many elements are coming, size the table up front so it never rehashes. Before Java 19 that meant computing expected / 0.75 yourself, which people often got wrong by passing expected directly. Since Java 19 there is a factory method that does the arithmetic:
Set<String> words = HashSet.newHashSet(expectedCount); // no rehash up to expectedCount elements
HashMap.newHashMap, LinkedHashSet.newLinkedHashSet and LinkedHashMap.newLinkedHashMap work the same way.
HashSet
A set is a collection without duplicates. HashSet implements it on a hash table. add first looks the element up and inserts it only if it is absent, returning false for a duplicate. contains is fast because it examines a single bucket instead of the whole collection.
The iterator visits the buckets one after another. Since hashing scatters elements across the table, the iteration order looks random. It isn't truly random, because it follows from the hash codes and the table size, but you can't control it and it may change between JDK versions. Use a HashSet only when order doesn't matter. When you want hash-set speed and insertion order, use LinkedHashSet, which article 88 covers.
TreeSet: a sorted set
A TreeSet works like a hash set with one important addition: it is sorted. You can insert elements in any order, and iteration always returns them in ascending order:
var sorter = new TreeSet<String>();
sorter.add("Ben");
sorter.add("Ava");
sorter.add("Cleo");
for (String s : sorter) System.out.println(s); // Ava, Ben, Cleo
Inside is a red-black tree, a self-balancing binary search tree. Each insertion places the element at its sorted position and rebalances the tree, so the tree's height stays around log₂ n. Finding, adding or removing an element takes about log₂ n comparisons: roughly 10 for a thousand elements and 20 for a million.
To sort, a tree set must compare its elements. Either the element class implements Comparable, or you pass a Comparator to the constructor. The articles on interfaces and comparators cover both.
var parts = new TreeSet<Item>(); // uses Item.compareTo
var byDescription = new TreeSet<Item>(Comparator.comparing(Item::description));
byDescription.addAll(parts);
Hash set or tree set?
A tree set is slower than a hash set. In typical word-counting benchmarks, inserting into a TreeSet takes several times longer than inserting into a HashSet. If you don't need the order, don't pay for it.
There is a subtler reason too. A hash function only has to scramble objects reasonably well. A comparator has to tell objects apart with total precision. Think about a set of rectangles. Comparing by area is wrong, because two different rectangles can have the same area, and the tree set would treat them as duplicates and drop one. A correct order exists, comparing x, then y, then width, then height, but it is tedious to write. A hash function for the same fields is one line: Objects.hash(x, y, width, height).
NavigableSet: finding neighbours
TreeSet implements NavigableSet (which extends SortedSet), and that interface is where a tree set really pays off. A hash set can only say yes or no. A tree set can also answer "what is the closest element?"

first()andlast()return the smallest and largest element. They throwNoSuchElementExceptionon an empty set.lower(v)andhigher(v)return the nearest element strictly below or abovev.floor(v)andceiling(v)also accept an element equal tov. All four returnnullwhen there is no such element.pollFirst()andpollLast()remove and return the smallest or largest element, ornullif the set is empty.headSet(v)returns elements< v,tailSet(v)returns elements>= v, andsubSet(a, b)returns elements in[a, b). These are live views, not copies. Article 89 explains views in detail.descendingSet()anddescendingIterator()go from largest to smallest.
These methods make problems like "find the next available time slot", "which price bracket is this amount in?" or "the nearest neighbour of a value" one-liners.
A complete example
import java.util.*;
public class Solution {
record Item(String description, int partNumber) implements Comparable<Item> {
public int compareTo(Item other) {
int diff = Integer.compare(partNumber, other.partNumber);
return diff != 0 ? diff : description.compareTo(other.description);
}
}
// a mutable class whose hashCode depends on its fields: dangerous inside a HashSet
static class Box {
int x, y;
Box(int x, int y) { this.x = x; this.y = y; }
void moveTo(int nx, int ny) { x = nx; y = ny; }
@Override public boolean equals(Object o) { return o instanceof Box b && x == b.x && y == b.y; }
@Override public int hashCode() { return Objects.hash(x, y); }
@Override public String toString() { return "Box(" + x + "," + y + ")"; }
}
public static void main(String[] args) {
// 1. hash codes and bucket indexes
for (String s : List.of("Lee", "lee", "eel", "Aa", "BB"))
System.out.printf("%-4s hashCode %8d hash %% 16: %2d%n", s, s.hashCode(), Math.floorMod(s.hashCode(), 16));
System.out.println("76268 % 128 = " + 76268 % 128);
// 2. HashSet vs TreeSet on the same words
String text = "the quick brown fox jumps over the lazy dog and the dog sleeps";
List<String> words = Arrays.asList(text.split(" "));
Set<String> hashed = new HashSet<>(words);
Set<String> sorted = new TreeSet<>(words);
System.out.println(words.size() + " words, " + hashed.size() + " distinct");
System.out.println("HashSet: " + hashed);
System.out.println("TreeSet: " + sorted);
System.out.println("add(\"fox\") again: " + hashed.add("fox") + ", contains(\"cat\"): " + hashed.contains("cat"));
// 3. pre-sizing (Java 19+)
Set<Integer> big = HashSet.newHashSet(1_000); // room for 1000 elements without rehashing
for (int i = 0; i < 1_000; i++) big.add(i);
System.out.println("newHashSet(1000) holds " + big.size());
// 4. mutating an element breaks the set
var boxes = new HashSet<Box>();
var box = new Box(5, 10);
boxes.add(box);
box.moveTo(0, 0); // hash code changes, bucket doesn't
System.out.println("after mutation: set " + boxes + ", contains(box) " + boxes.contains(box)
+ ", remove(new Box(0,0)) " + boxes.remove(new Box(0, 0)) + ", size " + boxes.size());
// 5. TreeSet with Comparable and with a Comparator
var parts = new TreeSet<Item>();
parts.add(new Item("Toaster", 1234));
parts.add(new Item("Widget", 4562));
parts.add(new Item("Router", 9912));
System.out.println("by part number: " + parts);
var byDescription = new TreeSet<Item>(Comparator.comparing(Item::description));
byDescription.addAll(parts);
System.out.println("by description: " + byDescription);
System.out.println("comparator(): " + (parts.comparator() == null ? "null (natural ordering)" : "custom"));
// 6. a comparator that disagrees with equals
var commands = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
commands.add("QUIT");
System.out.println("add(\"quit\"): " + commands.add("quit") + " -> " + commands);
System.out.println("commands.equals(Set.of(\"quit\")) " + commands.equals(Set.of("quit"))
+ ", Set.of(\"quit\").equals(commands) " + Set.of("quit").equals(commands));
// 7. NavigableSet: neighbours of a value
var scores = new TreeSet<>(List.of(40, 55, 70, 85, 90));
System.out.println("first " + scores.first() + ", last " + scores.last());
System.out.println("lower(70) " + scores.lower(70) + ", floor(70) " + scores.floor(70)
+ ", ceiling(71) " + scores.ceiling(71) + ", higher(90) " + scores.higher(90));
System.out.println("headSet(70) " + scores.headSet(70) + ", tailSet(70) " + scores.tailSet(70)
+ ", subSet(50, 86) " + scores.subSet(50, 86));
System.out.println("descendingSet " + scores.descendingSet());
System.out.println("pollFirst " + scores.pollFirst() + ", pollLast " + scores.pollLast() + " -> " + scores);
// 8. LinkedHashSet remembers insertion order
System.out.println("LinkedHashSet: " + new LinkedHashSet<>(words));
}
}
Lee hashCode 76268 hash % 16: 12
lee hashCode 107020 hash % 16: 12
eel hashCode 100300 hash % 16: 12
Aa hashCode 2112 hash % 16: 0
BB hashCode 2112 hash % 16: 0
76268 % 128 = 108
13 words, 10 distinct
HashSet: [over, quick, sleeps, lazy, jumps, brown, fox, the, and, dog]
TreeSet: [and, brown, dog, fox, jumps, lazy, over, quick, sleeps, the]
add("fox") again: false, contains("cat"): false
newHashSet(1000) holds 1000
after mutation: set [Box(0,0)], contains(box) false, remove(new Box(0,0)) false, size 1
by part number: [Item[description=Toaster, partNumber=1234], Item[description=Widget, partNumber=4562], Item[description=Router, partNumber=9912]]
by description: [Item[description=Router, partNumber=9912], Item[description=Toaster, partNumber=1234], Item[description=Widget, partNumber=4562]]
comparator(): null (natural ordering)
add("quit"): false -> [QUIT]
commands.equals(Set.of("quit")) true, Set.of("quit").equals(commands) false
first 40, last 90
lower(70) 55, floor(70) 70, ceiling(71) 85, higher(90) null
headSet(70) [40, 55], tailSet(70) [70, 85, 90], subSet(50, 86) [55, 70, 85]
descendingSet [90, 85, 70, 55, 40]
pollFirst 40, pollLast 90 -> [55, 70, 85]
LinkedHashSet: [the, quick, brown, fox, jumps, over, lazy, dog, and, sleeps]
The hash % 16 column shows the simple textbook reduction. A real HashSet first mixes the high bits into the low ones (h ^ (h >>> 16)), so "Lee" actually lands in bucket 13 of 16, not 12. The point of the demo is unchanged: different strings can share a bucket, and equal hash codes ("Aa", "BB") always do.
The HashSet line shows an arbitrary but repeatable order. The TreeSet line is alphabetical, and LinkedHashSet keeps the order of first appearance. In the mutation test, the box still prints as Box(0,0), yet neither contains nor remove can find it. It sits in the bucket for (5, 10).
Choosing a set implementation
| Need | Use | Cost of add / contains / remove |
|---|---|---|
| fast membership, any order | HashSet | O(1) average |
| fast membership, insertion order | LinkedHashSet | O(1) average |
| sorted order, range and neighbour queries | TreeSet | O(log n) |
| elements are enum constants | EnumSet (article 88) | O(1), a bit vector |
| fixed contents | Set.of(...) (article 89) | O(1), immutable |
| shared between threads | ConcurrentHashMap.newKeySet(), ConcurrentSkipListSet | covered in Part 10 |
Common questions
Why does my HashSet contain two objects that look equal?
Their class overrides equals but not hashCode, or the two methods disagree. The objects then land in different buckets, so equals is never called. Override both together, or use a record, which generates matching versions.
Is the iteration order of a HashSet stable?
It's repeatable within one JDK version for the same insertions and capacity, but it isn't specified and can change between versions or when the table is resized. Never rely on it. Use LinkedHashSet for insertion order or TreeSet for sorted order.
When is a TreeSet better than sorting a list?
When elements keep arriving and you need them in order at any time, or when you need neighbour queries such as floor, ceiling or headSet. If you only need the sorted result once, collecting into an ArrayList and calling sort is faster.
Why does my TreeSet drop elements that aren't equal?
A TreeSet treats elements as duplicates when the comparator returns 0, and it never calls equals. If your comparator compares only part of the data, such as a name, two different objects with the same name count as one. Add tie-breakers with thenComparing.
Can a HashSet contain null?
Yes, one null element. A TreeSet with natural ordering throws NullPointerException for null, and Set.of doesn't accept null at all.
API reference
java.util.HashSet<E>
| Method | Description |
|---|---|
HashSet() | empty hash set, 16 buckets, load factor 0.75 |
HashSet(Collection<? extends E> elements) | hash set holding all elements of the collection |
HashSet(int initialCapacity), HashSet(int initialCapacity, float loadFactor) | empty set with the given bucket count (rounded to a power of two) and load factor |
static <E> HashSet<E> newHashSet(int numElements) (Java 19) | empty set big enough for numElements without rehashing |
java.lang.Object
| Method | Description |
|---|---|
int hashCode() | any int, positive or negative; must be equal for objects that are equals |
java.util.TreeSet<E>
| Method | Description |
|---|---|
TreeSet(), TreeSet(Comparator<? super E> comparator) | empty tree set using natural ordering or the comparator |
TreeSet(Collection<? extends E> elements) | tree set holding the elements, in natural order |
TreeSet(SortedSet<E> s) | tree set holding the elements of s, with the same ordering |
java.util.SortedSet<E>
| Method | Description |
|---|---|
Comparator<? super E> comparator() | the comparator, or null for natural ordering |
E first(), E last() | smallest or largest element |
java.util.NavigableSet<E>
| Method | Description |
|---|---|
E higher(E value), E lower(E value) | least element > value, greatest element < value, or null |
E ceiling(E value), E floor(E value) | least element >= value, greatest element <= value, or null |
E pollFirst(), E pollLast() | remove and return the smallest or largest element, or null if empty |
Iterator<E> descendingIterator(), NavigableSet<E> descendingSet() | traverse in descending order |
Summary
- A hash table turns an element's
hashCodeinto a bucket index, then callsequalsonly within that bucket. Operations are O(1) on average. equalsandhashCodemust agree. Never change an element's hash-relevant fields while it is in a hash set.- The default load factor of 0.75 triggers rehashing into a table twice as large. Use
HashSet.newHashSet(n)to pre-size. TreeSetkeeps elements sorted in a red-black tree with O(log n) operations. Elements must beComparable, or you supply aComparator, and the ordering must be consistent withequals.NavigableSetadds neighbour queries (floor,ceiling,lower,higher), polling, range views and descending traversal.
Practice Questions
A class overrides equals but not hashCode. What happens when you put two equal instances into a HashSet?
Both are usually added. Object.hashCode gives the two instances different hash codes, so they most likely go to different buckets, and equals is never called to detect the duplicate. contains with a third equal instance will usually fail as well.
A HashSet is created with new HashSet<>(100). How many buckets does it have, and when does it first rehash?
128 buckets, because 100 is rounded up to the next power of two. It rehashes when the size exceeds 0.75 × 128 = 96. Note that new HashSet<>(100) does not guarantee room for 100 elements without rehashing. HashSet.newHashSet(100) does.
Why is a TreeSet with a comparator that compares rectangles by area a bug?
The tree set considers two elements duplicates when the comparator returns 0. Two different rectangles with equal areas would collapse into one, and the second add would silently return false.
Given TreeSet [10, 20, 30], what do floor(25), ceiling(25), lower(10) and higher(30) return?
floor(25) returns 20, ceiling(25) returns 30, lower(10) returns null, and higher(30) returns null.
Why might you prefer keys that implement Comparable in a HashMap or HashSet, even though hashing doesn't need ordering?
When many keys collide in one bucket, the bucket becomes a balanced tree. The tree can order Comparable keys properly, giving O(log n) lookups even under heavy collisions, such as a deliberate hash-flooding attack.
Previous: Java LinkedList vs ArrayList: Linked Lists, ListIterator and Array Lists
Next: Java Queues and Deques: ArrayDeque, LinkedList and PriorityQueue
Related reading
- Java LinkedList vs ArrayList: Linked Lists, ListIterator and Array Lists
- Java Collection Interfaces: List, Set, Queue, Map and Sequenced Collections
- The Java Collections Framework: Interfaces, Implementations and Iterators
- Java ArrayList: Generic Array Lists Explained
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.