Java TreeSet clone() Method Example

The clone() method of java.util.TreeSet class will create a shallow copy of the TreeSet.

Signature

public Object clone()

This method creates a shallow copy of this TreeSet. The elements themselves are not cloned.

Example

The following example shows the usage of java.util.TreeSet.clone() method.

import java.util.TreeSet;

public class CloneMethodTreeSetExample {
    public static void main(String args[])
    {
        // create an empty TreeSet
        TreeSet<String> treeSet1= new TreeSet<String>();
        
        // use add() method to add elements to the TreeSet
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");

        //Printing the elements of the TreeSet treeSet1
        System.out.println("**Elements of the treeSet1**");
        for(String temp:treeSet1)
        {
            System.out.println(temp);
        }
        
        // create another empty TreeSet
        TreeSet<String> treeSet2 = new TreeSet<String>();
        //Shallow copying of treeSet1 to treeSet2
                treeSet2 =(TreeSet)treeSet1.clone();
        
        //Printing the elements of the TreeSet treeSet2
        System.out.println("**Elements of the treeSet2**");
        for(String temp:treeSet2)
        {
            System.out.println(temp);
        }
    }
}

Output

**Elements of the treeSet1**
Element1
Element2
Element3
**Elements of the treeSet2**
Element1
Element2
Element3

Leave a Reply

Your email address will not be published. Required fields are marked *