Java Utility Library

Java TreeSet - clone() Method



The java.util.TreeSet.clone() method returns a shallow copy of this TreeSet instance. (The elements themselves are not cloned.)

Syntax

public Object clone()

Parameters

No parameter is required.

Return Value

Returns a shallow copy of this set.

Exception

NA

Example:

In the example below, the java.util.TreeSet.clone() method is used to create a clone of the given TreeSet.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //create a treeset
    TreeSet<Integer> Set1 = new TreeSet<Integer>();
    
    //populating Set1
    Set1.add(10);
    Set1.add(20);
    Set1.add(30);
    Set1.add(40);

    //print the content of Set1
    System.out.println("Set1 contains: "+ Set1); 

    //create a copy of Set1 into Set2
    Object Set2 = Set1.clone();

    //print the content of Set2
    System.out.println("Set2 contains: "+ Set2);  
  }
}

The output of the above code will be:

Set1 contains: [10, 20, 30, 40]
Set2 contains: [10, 20, 30, 40]

❮ Java.util - TreeSet