Java program to create the clone of the TreeSet collection

Given a TreeSet collection, we have to create its clone.
Submitted by Nidhi, on June 05, 2022

Problem Solution:

In this program, we will create a TreeSet collection with integer elements. Then we will use the clone() method to create a new TreeSet with the same elements.

Program/Source Code:

The source code to create the clone of the TreeSet collection is given below. The given program is compiled and executed successfully.

Example of TreeSet.clone() Method in Java

// Java program to create the clone of the 
// TreeSet collection

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String args[]) {
    TreeSet < Integer > tree = new TreeSet < Integer > ();

    tree.add(10);
    tree.add(20);
    tree.add(25);
    tree.add(30);

    TreeSet < Integer > cloneTree = (TreeSet < Integer > ) tree.clone();

    System.out.println("TreeSet 'tree': " + tree);
    System.out.println("Cloned TreeSet 'cloneTree': " + cloneTree);
  }
}

Output:

TreeSet 'tree': [10, 20, 25, 30]
Cloned TreeSet 'cloneTree': [10, 20, 25, 30]

Explanation:

In the above program, we imported the "java.util.*", "java.io.*" packages to use the TreeSet class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created a TreeSet collection tree and added integer elements using add() method. Then we created a new TreeSet with the same elements using the clone() method. After that, we printed both collections.

Java TreeSet Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.