how to create a clone of a TreeSet using the collections in java
Previous | Home | Next |
In this example we will see how to create the clone of a TreeSet using collections.
For creating a TreeSet we have to import the java.util package in which we have the class java.util.TreeSet which contains the definition and various that can be performed on a TreeSet. In this example we have created a class named CollectionExample in which we have created a TreeSet and added some elements to it.
In this example we have used the clone() method on the object of TreeSet for creating the clone of the TreeSet. The syntax for the clone() method is ,
Object clone()
This method returns the shallow copy of the TreeSet object upon which this method is invoked.
In this example we have created a class name CollectionExample in which we have created a TreeSet and add some elements to it by using the add() method on the object of the TreeSet i.e. ts. Again we have created another TreeSet object ts1 which is empty. Then we stored the elements returned by the clone() method on the ts . The following statments in the given example demonstrates the same,TreeSet<Integer> ts1=new TreeSet<Integer>();
Object objclone= ts.clone();
ts1=(TreeSet<Integer>)objclone;
The third statement uses the typecasting for converting the object elements returned by the clone method to the TreeSet<Integer> type.
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
TreeSet<Integer> ts=new TreeSet<Integer>();
ts.add(2);
ts.add(4);
ts.add(7);
ts.add(8);
ts.add(1);
ts.add(9);
System.out.println("The objects of the tree set are as follows: ");
System.out.println(ts);
TreeSet<Integer> ts1=new TreeSet<Integer>();
Object objclone= ts.clone();
ts1=(TreeSet<Integer>)objclone;
System.out.println("The contents of the cloned TreeSet are: "+ts1);
}
}
The output of the above code is as follows:
The objects of the tree set are as follows:
[1, 2, 4, 7, 8, 9]
The contents of the cloned TreeSet are: [1, 2, 4, 7, 8, 9]
Previous | Home | Next |