Write a Java program to Create the clone of the TreeSet collection


The code demonstrates how to create a shallow copy or clone of a TreeSet in Java. In the Clone_TreeSet class, a TreeSet object called col is created to store strings. Strings such as "Blue", "Red", "Green", "White", "Orange", "Yellow", and "Pink" are added to the col set using the add method.

The System.out.println statement is used to print the elements in the col set, which will be displayed in a sorted order as TreeSet automatically sorts its elements based on their natural order or using a custom comparator if provided.

The col.clone() method is used to create a shallow copy or clone of the col set. The clone method returns a new TreeSet object with the same elements and sorted order as the original col set. Note that the clone method returns a shallow copy, which means that the elements themselves are not cloned, but only the references to the elements are copied.

The cloned TreeSet object is assigned to a new TreeSet variable called clone_col. The System.out.println statement is used to print the elements in the clone_col set, which will also be displayed in a sorted order.

Note: The clone method in Java creates a shallow copy of an object, which means that the object itself is not cloned, but only the references to its internal objects are copied. If the original object contains mutable objects, changes made to the mutable objects in the cloned object will also be reflected in the original object. To create a deep copy of an object, where the objects themselves are cloned recursively, a custom implementation of cloning logic needs to be implemented.

Source Code

import java.io.*;
import java.util.*;
public class Clone_TreeSet
{
	public static void main(String args[])
	{
		TreeSet <String> col = new TreeSet <String>();
		col.add("Blue");
		col.add("Red");
		col.add("Green");
		col.add("White");
		col.add("Orange");
		col.add("Yellow");
		col.add("Pink");
		TreeSet <String> clone_col = (TreeSet<String>)col.clone();
		System.out.println("TreeSet Elements : " + col);
		System.out.println("Cloned TreeSet Elements : " + clone_col);
	}
}

Output

TreeSet Elements : [Blue, Green, Orange, Pink, Red, White, Yellow]
Cloned TreeSet Elements : [Blue, Green, Orange, Pink, Red, White, Yellow]