Java HashSet

Beginner
9 min read
Updated: Nov 2026
3 examples
java.util.HashSet

Definition and Usage

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 HashSet rejects 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.

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.

How Hashing Keeps Elements Unique

A HashSet is an array of buckets. To add an element, Java follows the same path every time:

StepWhat happens
1. HashJava 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 bucketIf 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. GrowThe 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.

HashSet vs LinkedHashSet vs TreeSet

All three implement Set and reject duplicates, but they differ in order, speed, and null support:

ClassOrderCost (add / contains)Allows null?
HashSetNo guaranteed orderO(1) on averageYes (one null)
LinkedHashSetInsertion orderO(1) on average, a little more memoryYes (one null)
TreeSetSorted (natural order or a Comparator)O(log n)No (by default)

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.

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:

OperationCostWhy
add(e), remove(o), contains(o)Constant on averageThe hash code points straight to one bucket
size(), isEmpty()Constant timeThe count is stored
addAll(c), retainAll(c), removeAll(c), containsAll(c)Grows with the collection involvedEach element is hashed or looked up once
iterator() loop, toArray(), clone()Grows with the table size plus the elementsEmpty buckets are skipped, so a huge capacity with few elements loops slowly

Java Examples

Example 1 — Find Duplicate IDs with add()

Feed an array of ticket IDs into a HashSet. The return value of add() tells you immediately when an ID has been seen before.

Java
import java.util.HashSet;
import java.util.Set;

public class HashSetHubDuplicates {
    public static void main(String[] args) {
        int[] ids = {42, 7, 19, 7, 42, 100, 3};
        Set<Integer> seen = new HashSet<>();

        for (int id : ids) {
            if (!seen.add(id)) {
                System.out.println("duplicate: " + id);
            }
        }

        System.out.println("unique: " + seen);
        System.out.println("size: " + seen.size());
        System.out.println("contains 100: " + seen.contains(100));
    }
}

How It Works

  1. 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.
  2. Seven inputs, five elements. Only the first copy of each value is stored, which is why size() is 5.
  3. 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));
    }
}

How It Works

  1. Copy first. new HashSet<>(morning) makes an independent set, because addAll(), retainAll(), and removeAll() change the set they are called on.
  2. 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.
  3. 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)));
    }
}

How It Works

  1. 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.
  2. Lookup fails too. A brand-new PlainSeat(3, 12) has its own identity hash code, so contains() cannot find it and returns false.
  3. 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.

Next: Java HashSet Methods by Group

GroupMethods
Add and look upadd(), addAll(), contains(), containsAll()
Remove and filterremove(), removeAll(), removeIf(), retainAll(), clear()
Size and statesize(), isEmpty()
Loop and convertiterator(), spliterator(), toArray()
Copy, compare, and hashclone(), equals(), hashCode()

Full list with short descriptions: Java HashSet Methods index (/java/hashset/method).

Frequently Asked Questions

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.

Browse every HashSet method

Open the methods index for categorized guides with examples and FAQs.

HashSet Methods Index →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful