how to create a clone of a HashSet using Collections in java
Previous | Home | Next |
In this example we will see how we can create the clone of the HashSet.
For creating a HashSet we have to import the java.util package in which the HashSet class is defined. In this example we have created a class name CollectionExample in which we created a HashSet and added various elements to it.
In this example for creating the clone of the HashSet, we have used the following method on the object of the HashSet,
Object clone()
This method returns the shallow copy of the HashSet created.
In the given example we have created a HashSet and added some elements to it. We also created a second HashSet which is empty. Then we invoked the clone() method on the object of the HashSet set and stored the values returned by this method to the HashSet set2 by casting the Object elements returned by clone() method to HashSet<Integer>.
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
HashSet<Integer> set=new HashSet<Integer>(); // creating a HashSet named set
set.add(1); // adding elements to the HashSet
set.add(3);
set.add(4);
set.add(5);
set.add(7);
set.add(1);
set.add(4);
set.add(7);
//Iterator<Integer> itr=set.iterator();
System.out.println("The contents of the set are:"); //displaying the contents of the HashSet
System.out.println(set);
HashSet<Integer> set2=new HashSet<Integer>();
set2=(HashSet<Integer>)set.clone();
System.out.println("The contents of the cloned HashSet are: ");
System.out.println(set2);
}
}
The output of the above written code is the following one :
The contents of the set are:
[1, 3, 4, 5, 7]
The contents of the cloned HashSet are:
[1, 3, 4, 5, 7]
Previous | Home | Next |