Java HashSet clear() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

In Java, clear() removes every element from a HashSet. Afterwards size() is 0, isEmpty() is true, and contains() is false for everything.

The set object itself survives, so you can keep adding to it. Every variable that refers to the same set sees the empty state, while a copy made earlier keeps its own elements.

An instance method of java.util.HashSet (class since Java 1.2): a set of unique elements kept in a hash table, with no guaranteed order, one null element allowed, and no thread safety.

Syntax

No arguments; returns nothing.

Java
Set<String> cart = new HashSet<>();
cart.add("milk");
cart.clear();
System.out.println(cart);   // []
CallWhat it does
set.clear()Removes every element; the set stays usable.
set = new HashSet<>()Points the variable at a new set; other references keep the old one.
set.isEmpty()true right after clear().
set.removeAll(set)Also empties the set, but clear() says what you mean.

In OpenJDK, clear() empties the internal table but keeps its current length, so a set that once grew large keeps that capacity. This is an implementation detail; create a new set if you want to release the memory.

Library declarations
Java
// java.util.HashSet<E>
public void clear()

// Declared in Set<E> and Collection<E>

Parameters

ParameterDescription
Noneclear() takes no parameters.

Return Value

Return ValueDescription
voidNothing. The set is empty afterwards.

Compare with Similar Methods

Removing many elements:

MethodHow it differs
remove(o)Removes one element.
removeIf(test)Removes only the elements that match.
isEmpty()Confirms the set is empty.
clone()Take a copy first if you still need the elements.

Java Examples

Example 1 — Empty a Shopping Cart and Reuse It

Print a cart, clear it, test it, and add a new item to the same set.

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

public class HashSetClearDemo {
    public static void main(String[] args) {
        Set<String> cart = new HashSet<>();
        cart.add("milk");
        cart.add("eggs");
        cart.add("bread");
        System.out.println("before: " + cart + " size " + cart.size());

        cart.clear();
        System.out.println("after: " + cart + " size " + cart.size());
        System.out.println("isEmpty: " + cart.isEmpty() + ", has milk: " + cart.contains("milk"));

        cart.add("tea");
        System.out.println("reused: " + cart);
    }
}

How It Works

  1. Three items. The cart prints its elements in bucket order, with a size of 3.
  2. All gone. After clear() the set prints as [] and has size 0.
  3. Lookups fail. contains("milk") is now false, and isEmpty() confirms there is nothing left.
  4. Same object, ready again. clear() does not destroy the set, so add("tea") works on the very same cart.

Example 2 — clear() Affects Every Reference, Not Copies

Clear a set that a second variable also points to, and compare with an independent copy.

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

public class HashSetClearShared {
    public static void main(String[] args) {
        Set<String> open = new HashSet<>();
        open.add("door");
        open.add("window");

        Set<String> sameSet = open;
        Set<String> snapshot = new HashSet<>(open);

        open.clear();
        System.out.println("sameSet size: " + sameSet.size());
        System.out.println("snapshot size: " + snapshot.size() + ", has door: " + snapshot.contains("door"));
        System.out.println("same object: " + (open == sameSet));
    }
}

How It Works

  1. Two names, one set. sameSet = open copies only the reference, so both variables lead to the same object.
  2. The alias sees it. Clearing through open also empties what sameSet looks at, so its size is 0.
  3. A copy is independent. new HashSet<>(open) built snapshot before the clear, so it still holds both elements.
  4. Identity check. open == sameSet is true because the == operator compares references.

Example 3 — Reuse One Set Between Batches

Count the unique words in three batches with a single set that is cleared before each batch.

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

public class HashSetClearBatches {
    public static void main(String[] args) {
        String[][] batches = {
            {"a", "b", "a"},
            {"x", "x", "x", "y"},
            {}
        };

        Set<String> unique = new HashSet<>();
        for (int i = 0; i < batches.length; i++) {
            unique.clear();
            for (String word : batches[i]) {
                unique.add(word);
            }
            System.out.println("batch " + (i + 1) + ": " + unique.size() + " unique");
        }
    }
}

How It Works

  1. One set, three rounds. The same unique object is created once, and clear() resets it at the start of every round.
  2. Round 1. The words a, b, a collapse to two distinct values.
  3. Round 2. The leftovers from round 1 are gone, so the x, x, x, y batch counts only x and y.
  4. Round 3. The empty batch adds nothing, so after the clear the size stays 0.

Frequently Asked Questions

Call set.clear(). It removes every element and leaves an empty set that you can keep using.
clear() empties the existing object, so every reference sees the change. new HashSet<>() makes a separate object, and other references still point to the old set.
No. It only removes the set's references to them. Objects that are used elsewhere in your program stay alive.
No. Calling it on an empty set does nothing.
Clearing the set changes it structurally while a for-each loop is iterating over it. Finish the loop first, or iterate over a copy.

Next: clone()

Make a shallow copy of the set.

clone() tutorial →

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