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();
Call
What 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
Parameter
Description
None
clone() takes no parameters.
Return Value
Return Value
Description
Object
A shallow copy of this set. Cast it to HashSet<E>.
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));
}
}
Output
original size: 1, has red: false
copy size: 3, has red: true, has blue: true
same object: false
How It Works
Cast required.clone() is declared to return Object, so the result is cast to HashSet<String>; the annotation silences the unchecked warning.
Separate sets. Adding "blue" to the copy and removing "red" from the original affect only the set they were called on.
Counting it up. The original ends with one element (green), and the copy with three (red, green, blue).
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));
}
}
Output
original element: log-edited
same element object: true
sets are different objects: true
How It Works
One element, two sets. After clone(), both sets hold a reference to the very same StringBuilder; only the set structure was copied.
Edit through the copy.append("-edited") changes that one shared object, so the original's element now reads "log-edited".
Reference comparison.fromOriginal == fromCopy is true, which proves there is only one element object.
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());
}
}
Output
equal copies: true
from a list: 2 elements
copy of a Set variable: 3
How It Works
Same contents. The clone and the constructor copy both hold ann, bo, and cy, so equals() reports true.
The constructor takes any collection.new HashSet<>(list) copies a List and drops the repeated "b", giving two elements.
No clone on Set. The variable shared is declared as Set, so shared.clone() would not compile; the constructor works for any Set.
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.