In Java, HashSet (in java.util, since Java 1.2) stores unique elements in a hash table. It is the most common implementation of the Set interface: a collection with no duplicates. Inside, it is backed by a HashMap whose keys are your elements, so add(), remove(), and contains() run in constant time on average, no matter how many elements the set holds.
It implements Set, Collection, Iterable, Cloneable, and Serializable. A HashSetrejects duplicates, allows one null, and makes no promise about order. Because a set has no positions, there is no get(index): you ask whether an element is present, or loop over all of them. The HashSet Methods index lists every guide.
Not ordered and not thread-safe.
Never rely on the order a HashSet prints in: it depends on hash codes and the table size, and it can change when the set grows. A HashSet is also not thread-safe: share it between threads only with Collections.synchronizedSet(...) or ConcurrentHashMap.newKeySet(). Its iterators are fail-fast: changing the set during a loop (other than through iterator().remove()) usually throws ConcurrentModificationException. Use removeIf() to delete while filtering.
Syntax
Java Syntax
Import the class, then create a set. Declaring the variable as Set keeps your code flexible:
Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
Set<String> tags = new HashSet<>(); // empty
Set<Integer> ids = new HashSet<>(1000); // starting capacity 1000
Set<Integer> copy = new HashSet<>(Arrays.asList(3, 1, 3)); // 1 and 3, duplicate dropped
tags.add("java"); // true: it was new
tags.add("java"); // false: already present
System.out.println(tags.contains("java")); // true
The number in new HashSet<>(1000) is a starting capacity (the number of buckets), not a size. Pass it when you already know roughly how many elements are coming, so the table does not have to grow again and again. Java 9's Set.of(...) creates a small unmodifiable set that rejects null and duplicates; use new HashSet<>() when you need to add and remove elements later.
Concept
How Hashing Keeps Elements Unique
A HashSet is an array of buckets. To add an element, Java follows the same path every time:
Step
What happens
1. Hash
Java calls hashCode() on the element and mixes the bits to get a bucket number between 0 and the table length minus 1.
2. Look in the bucket
If the bucket is empty, the element goes in. Otherwise it is compared with each element already there.
3. Compare with equals()
A match means a duplicate: add() returns false and the set is unchanged. No match means a collision, and the new element is chained next to the others.
4. Grow
The default table has 16 buckets and a load factor of 0.75. When more than 12 elements are stored, the table doubles and elements are redistributed.
This is why equal elements must have equal hash codes. If a class overrides equals() but not hashCode(), two equal objects land in different buckets and both stay in the set. String, Integer, and the other standard value classes already follow the rule; for your own classes, override equals() and hashCode() together, and never change a field they use while the object is inside a set. Since Java 8, a bucket that collects many colliding elements turns into a balanced tree, which protects the set from very slow lookups.
Reference
HashSet vs LinkedHashSet vs TreeSet
All three implement Set and reject duplicates, but they differ in order, speed, and null support:
Pick HashSet by default for membership tests and de-duplication. Reach for LinkedHashSet when output order must match input order, and for TreeSet when you need sorted elements or range queries. For key/value pairs instead of single elements, see HashMap, which a HashSet uses behind the scenes.
Reference
What Is Fast and What Is Slow
Operations that go through the hash code are fast; operations that must look at many elements grow with the set:
add() answers the question. It returns true when the element was new and false when it was already present, so the second 7 and the second 42 are reported as duplicates.
Seven inputs, five elements. Only the first copy of each value is stored, which is why size() is 5.
Order follows the buckets. Small integers hash to themselves, and with 16 buckets 19 and 3 share bucket 3, 100 goes to bucket 4, 7 to bucket 7, and 42 to bucket 10, so the set prints [19, 3, 100, 7, 42] rather than the insertion order. Do not depend on this order.
Example 2 — Union, Intersection, and Difference of Two Sets
Two groups of room numbers show how addAll(), retainAll(), and removeAll() behave like set union, intersection, and difference. Each step works on a copy so the originals stay intact.
Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class HashSetHubOperations {
public static void main(String[] args) {
Set<Integer> morning = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> evening = new HashSet<>(Arrays.asList(4, 5, 6, 7));
Set<Integer> union = new HashSet<>(morning);
union.addAll(evening);
Set<Integer> both = new HashSet<>(morning);
both.retainAll(evening);
Set<Integer> onlyMorning = new HashSet<>(morning);
onlyMorning.removeAll(evening);
System.out.println("union: " + union);
System.out.println("intersection: " + both);
System.out.println("difference: " + onlyMorning);
System.out.println("subset check: " + union.containsAll(both));
}
}
Copy first.new HashSet<>(morning) makes an independent set, because addAll(), retainAll(), and removeAll() change the set they are called on.
Union and intersection.addAll() adds every element of evening, skipping 4 and 5, which are already there; retainAll() keeps only the elements that also appear in evening.
Difference and subset.removeAll() deletes 4 and 5, leaving 1, 2, 3, and containsAll() confirms every element of both is inside union. These small integers happen to print in ascending order; that is a side effect of their hash codes, not a guarantee.
Example 3 — Why Custom Classes Need equals() and hashCode()
Put two equal-looking seats into a HashSet twice: first with a plain class, then with a class that overrides equals() and hashCode().
Java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class HashSetHubEqualsHash {
static class PlainSeat {
final int row, number;
PlainSeat(int row, int number) { this.row = row; this.number = number; }
}
static class Seat {
final int row, number;
Seat(int row, int number) { this.row = row; this.number = number; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Seat)) return false;
Seat other = (Seat) o;
return row == other.row && number == other.number;
}
@Override
public int hashCode() { return Objects.hash(row, number); }
}
public static void main(String[] args) {
Set<PlainSeat> plain = new HashSet<>();
plain.add(new PlainSeat(3, 12));
plain.add(new PlainSeat(3, 12));
System.out.println("plain size: " + plain.size());
System.out.println("plain contains: " + plain.contains(new PlainSeat(3, 12)));
Set<Seat> seats = new HashSet<>();
seats.add(new Seat(3, 12));
seats.add(new Seat(3, 12));
System.out.println("seat size: " + seats.size());
System.out.println("seat contains: " + seats.contains(new Seat(3, 12)));
}
}
Identity by default. Without overrides, equals() and hashCode() compare object identity, so two PlainSeat objects with the same numbers are different elements and the set holds both.
Lookup fails too. A brand-new PlainSeat(3, 12) has its own identity hash code, so contains() cannot find it and returns false.
Overrides fix both.Seat computes its hash code from row and number and compares the same fields in equals(), so the second add is a duplicate and contains() finds a matching seat.
HashSet is a class in java.util that stores unique elements in a hash table. It implements the Set interface, rejects duplicates, and checks membership, adds, and removes in constant time on average. Internally it is backed by a HashMap.
No. Elements sit in buckets chosen from their hash codes, and the iteration order is not guaranteed and can change when the set grows. Use LinkedHashSet for insertion order or TreeSet for sorted elements.
Yes. A HashSet accepts one null element, because null is simply stored in a fixed bucket. Adding null a second time is treated as a duplicate and add() returns false.
It computes the hash code of the new element to find a bucket, then compares it with the elements already in that bucket using equals(). Two elements are duplicates only when their hash codes match and equals() returns true, so custom classes must override both methods together.
No. Wrap it with Collections.synchronizedSet(...) and synchronize manually while iterating, or use ConcurrentHashMap.newKeySet() for concurrent access. Its iterators are fail-fast and throw ConcurrentModificationException if the set changes during a loop.