Program to perform a deep copy of a HashSet in Java
We can use Copy Constructor in HashSet to achieve Deep copy. Bypassing the original set on the new Set’s constructor. For example, we have a set of Strings and we want to create a deep copy of it.
Below is the implementation of creating Deep Copy Using Copy Constructor:
Java
// Java Program to perform a deep copy of a HashSet import java.io.*; import java.util.Arrays; import java.util.HashSet; class GFG { public static void main(String[] args) { // Given Set of Strings HashSet<String> Set = new HashSet<>( Arrays.asList( "Geeks" , "hello" , "gfg" )); // Deep copy using copy constructor in Hashset. HashSet<String> copied_set = new HashSet<>(Set); // test the Set copied_set.remove( "Geeks" ); // show the results System.out.println( "Original Set " + Set); System.out.println( "Copied Set" + copied_set); } } |
Output
Original Set [Geeks, gfg, hello] Copied Set[gfg, hello]
Explanation of the above Program:
- This Java program performs a deep copy of a HashSet.
- It starts with a given set of strings.
- Using the copy constructor, it creates a new HashSet named
copied_set
as a deep copy of the original set. - The program then removes “Geeks” from the copied set to demonstrate independence.
- Finally, it prints the original and copied sets. In simpler terms, it duplicates a set to create an independent copy, and changes to one set don’t affect the other.
Deep Copy of a HashSet in Java
HashSet is used to store a unique set of values in Java. It is a class that stores values and provides efficient access. As we know Java uses call-by-reference. So, if we copy a Set and want to make changes to the copied Set, we want it to not affect the element of the original Set. But if it is a shallow copy, then it affects the original set. So, we use a Deep copy of a set, which creates a separate memory for the given set.
If you want to know more about the concept of shallow and deep copy you can go through shallow and deep copy.