Home »
Java programming language
Java TreeSet clone() Method with Example
TreeSet Class clone() method: Here, we are going to learn about the clone() method of TreeSet Class with its syntax and example.
Submitted by Preeti Jain, on February 20, 2020
TreeSet Class clone() method
- clone() method is available in java.util package.
- clone() method is used to clone or copy this TreeSet instance.
- clone() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- clone() method does not throw an exception at the time of cloning an object.
Syntax:
public Object clone();
Parameter(s):
- It does not accept any parameter.
Return value:
The return type of the method is Object, it returns cloned TreeSet instance.
Example:
// Java program to demonstrate the example
// of Object clone() method of TreeSet
import java.util.*;
public class CloneOfTreeSet {
public static void main(String[] args) {
// Instantiates a TreeSet object
TreeSet < String > tree_set = new TreeSet < String > ();
TreeSet < String > clone_set = new TreeSet < String > ();
// By using add() method is to add
// the given object of this
// TreeSet
tree_set.add("C");
tree_set.add("C++");
tree_set.add("JAVA");
tree_set.add("PHP");
tree_set.add("SFDC");
// Display TreeSet
System.out.println("TreeSet: " + tree_set);
System.out.println("Clone TreeSet: " + clone_set);
// By using clone() method is to
// clone this TreeSet
clone_set = (TreeSet) tree_set.clone();
// Display Cloned TreeSet
System.out.println("tree_set.clone(): " + clone_set);
}
}
Output
TreeSet: [C, C++, JAVA, PHP, SFDC]
Clone TreeSet: []
tree_set.clone(): [C, C++, JAVA, PHP, SFDC]