1. Introduction
In Java, HashSet is part of the Collections Framework and is used to store unique elements. Sometimes, you might want to create an exact copy of a HashSet. The clone() method of the HashSet class can be used for this purpose, creating a shallow copy of the set.
2. Program Steps
1. Create a HashSet and populate it with elements.
2. Print the original HashSet to the console.
3. Use the clone() method to create a copy of the HashSet.
4. Print the cloned HashSet to ensure it has the same elements as the original.
5. Confirm the original and the cloned HashSet are not the same object.
3. Code Program
import java.util.HashSet;
public class HashSetClone {
public static void main(String[] args) {
// Step 1: Create a HashSet and populate it with elements
HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Step 2: Print the original HashSet to the console
System.out.println("Original HashSet: " + fruits);
// Step 3: Use the clone() method to create a copy of the HashSet
HashSet<String> clonedFruits = (HashSet<String>) fruits.clone();
// Step 4: Print the cloned HashSet to ensure it has the same elements as the original
System.out.println("Cloned HashSet: " + clonedFruits);
// Step 5: Confirm the original and the cloned HashSet are not the same object
System.out.println("Are the original and cloned HashSets the same object? " + (fruits == clonedFruits));
}
}
Output:
Original HashSet: [Banana, Cherry, Apple] Cloned HashSet: [Banana, Cherry, Apple] Are the original and cloned HashSets the same object? false
4. Step By Step Explanation
Step 1: A HashSet named fruits is created and some elements are added to it.
Step 2: The original HashSet is printed to the console, showing its elements.
Step 3: The clone() method is called on the fruits HashSet, creating a shallow copy named clonedFruits.
Step 4: The cloned HashSet is printed to the console, showing it has the same elements as the original HashSet.
Step 5: A comparison is made to check if the original and the cloned HashSet are the same object, which returns false, indicating that clone() creates a new object.