Java HashSet clone() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

In Java, clone() returns a shallow copy of a HashSet: a new set object that holds the same elements. Adding or removing elements in the copy does not change the original, and the other way round.

The elements themselves are not copied. Both sets point to the same element objects, so changing a mutable element is visible through both sets.

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; it returns Object, so you cast the result.

Java
HashSet<String> original = new HashSet<>();
original.add("red");
@SuppressWarnings("unchecked")
HashSet<String> copy = (HashSet<String>) original.clone();
CallWhat it does
(HashSet<String>) set.clone()A shallow copy; needs a cast and gives an unchecked warning.
new HashSet<>(set)The copy constructor: no cast, works for any collection.
copy.addAll(set)Copy into a set you already have.
set.clone()Only available when the variable is declared as HashSet, not as Set.

Most code prefers new HashSet<>(set) because it needs no cast. From JDK 19 on, the internal table of a copy can be sized differently, so a copy may print in a different order than the original.

Library declarations
Java
// java.util.HashSet<E> implements Cloneable
public Object clone()

Parameters

ParameterDescription
Noneclone() takes no parameters.

Return Value

Return ValueDescription
ObjectA shallow copy of this set. Cast it to HashSet<E>.

Compare with Similar Methods

Ways to copy a set:

MethodHow it differs
addAll(c)Copies the elements into an existing set.
toArray()Copies into an array instead.
Collections.unmodifiableSet(s)A read-only view of the same set, not a copy.
ArrayList.clone()The same idea for a list.

Java Examples

Example 1 — Copy a Set and Change Only the Copy

Clone a set, add to the copy, remove from the original, and compare the two.

Java
import java.util.HashSet;

public class HashSetCloneDemo {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        HashSet<String> original = new HashSet<>();
        original.add("red");
        original.add("green");

        HashSet<String> copy = (HashSet<String>) original.clone();
        copy.add("blue");
        original.remove("red");

        System.out.println("original size: " + original.size() + ", has red: " + original.contains("red"));
        System.out.println("copy size: " + copy.size() + ", has red: " + copy.contains("red") + ", has blue: " + copy.contains("blue"));
        System.out.println("same object: " + (original == copy));
    }
}

How It Works

  1. Cast required. clone() is declared to return Object, so the result is cast to HashSet<String>; the annotation silences the unchecked warning.
  2. Separate sets. Adding "blue" to the copy and removing "red" from the original affect only the set they were called on.
  3. Counting it up. The original ends with one element (green), and the copy with three (red, green, blue).
  4. Different objects. original == copy is false because clone() created a new set object.

Example 2 — A Shallow Copy Shares Its Elements

Edit an element through the copy and read it through the original.

Java
import java.util.HashSet;

public class HashSetCloneShallow {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        HashSet<StringBuilder> original = new HashSet<>();
        original.add(new StringBuilder("log"));

        HashSet<StringBuilder> copy = (HashSet<StringBuilder>) original.clone();

        StringBuilder fromCopy = copy.iterator().next();
        fromCopy.append("-edited");

        StringBuilder fromOriginal = original.iterator().next();
        System.out.println("original element: " + fromOriginal);
        System.out.println("same element object: " + (fromOriginal == fromCopy));
        System.out.println("sets are different objects: " + (original != copy));
    }
}

How It Works

  1. One element, two sets. After clone(), both sets hold a reference to the very same StringBuilder; only the set structure was copied.
  2. Edit through the copy. append("-edited") changes that one shared object, so the original's element now reads "log-edited".
  3. Reference comparison. fromOriginal == fromCopy is true, which proves there is only one element object.
  4. A safe choice of element. StringBuilder uses identity for hashCode(), so editing it does not make it unfindable; a key class whose hash depends on its fields would be a problem.

Example 3 — Clone or the Copy Constructor?

Make the same copy both ways, then copy from a list and from a variable declared as Set.

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

public class HashSetCloneVsCopy {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>(Arrays.asList("ann", "bo", "cy"));

        HashSet<String> viaClone = (HashSet<String>) names.clone();
        Set<String> viaConstructor = new HashSet<>(names);
        System.out.println("equal copies: " + viaClone.equals(viaConstructor));

        List<String> list = Arrays.asList("b", "a", "b");
        Set<String> fromList = new HashSet<>(list);
        System.out.println("from a list: " + fromList.size() + " elements");

        Set<String> shared = names;
        Set<String> viaSetVariable = new HashSet<>(shared);
        System.out.println("copy of a Set variable: " + viaSetVariable.size());
    }
}

How It Works

  1. Same contents. The clone and the constructor copy both hold ann, bo, and cy, so equals() reports true.
  2. The constructor takes any collection. new HashSet<>(list) copies a List and drops the repeated "b", giving two elements.
  3. No clone on Set. The variable shared is declared as Set, so shared.clone() would not compile; the constructor works for any Set.
  4. No cast needed. Only the clone() line needs the unchecked cast and the annotation on main.

Frequently Asked Questions

Use new HashSet<>(set), or cast the result of set.clone(). Both produce a shallow copy that you can change without affecting the original.
The set structure is copied, but the elements are not. Both sets refer to the same element objects, so mutating an element is visible through both.
clone() is declared to return Object. Cast it with (HashSet<String>) and add @SuppressWarnings("unchecked") if you want to hide the compiler warning.
Most code uses new HashSet<>(set): it needs no cast and works for any collection. clone() only works on a variable declared as HashSet.
Not guaranteed. The order depends on the hash codes and the table size, and the copy may be sized differently, especially on JDK 19 and later.

Next: contains()

Check whether an element is in the set.

contains() 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.

10 people found this page helpful