Skip to content

How to Copy Merge and Clone TreeSet in Java

This example shows how to copy one TreeSet to another TreeSet, merge two TreeSet objects and clone a TreeSet object using constructor, the addAll method and the clone method.

How to copy one TreeSet object to another TreeSet object?

We can copy one TreeSet object to another using the copy constructor.

This TreeSet constructor creates a new TreeSet object containing all the elements of the specified collection object. Since the TreeSet class is a child class of the Collection interface, we can pass the TreeSet object in this constructor.

Output

As we can see from the output, all the elements of the TreeSet object are copied into the new TreeSet object.

We can also create a new TreeSet using the default constructor, and then use the addAll method to add all elements of one TreeSet to another.

How to merge two TreeSet objects?

The addAll method of the TreeSet class adds all the elements of the specified collection object to this TreeSet object.

We can use the addAll method to merge two TreeSet objects as given below.

Output

As we can see from the output, the element “3” is not added while merging. Please note that the elements that are already present in the first TreeSet object will not be added from the second TreeSet. The merged TreeSet object will only contain unique elements.

How to clone a TreeSet object using the clone method?

The clone method of the TreeSet class creates a shallow copy of the TreeSet object.

Output

Please note that the clone method creates a shallow copy of a TreeSet object, not a deep copy. In other words, only the element references are copied, not the actual objects.

Let’s see an example of what is a shallow copy.

Output

This example is a part of the TreeSet in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.