Java HashSet clone() Method
Example
Create a copy of a set:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
HashSet<String> carsCopy = (HashSet<String>) cars.clone();
carsCopy.add("Toyota");
System.out.println(cars.contains("Toyota"));
System.out.println(carsCopy.contains("Toyota"));
}
}
Definition and Usage
The clone() method creates a copy of the set.
The copy is a new set, so adding or removing items in the copy does not change the original set. In the example, "Toyota" is only added to the copy.
The method returns an Object, so you must cast it to a HashSet to use it as one.
Note: This is a shallow copy. If the items are objects, both sets refer to the same objects.
Syntax
public Object clone()
Parameter Values
None.
Technical Details
| Returns: | A copy of the set, as an Object. |
|---|