Skip to content

Copy Merge or Clone LinkedHashSet in Java Example

This example shows how to copy, merge, or clone LinkedHashSet in Java. This example also shows how to copy, merge, or clone LinkedHashSet using constructor, addAll method, and clone method.

How to copy one LinkedHashSet to another LinkedHashSet object (clone LinkedHashSet)?

There are several ways using which we can copy one linked hash set object to another as given below.

1. Using the constructor

The LinkedHashSet class in Java provides a constructor that accepts a collection object.

This constructor creates a new LinkedHashSet object containing all elements of the specified collection object.

Output

2. Using the addAll method

We can also create an empty LinkedHashSet object and then use the addAll method to add all elements of one linked hash set object to another as given below.

Output

3. Using the clone method

The LinkedHashSet clone method can be used to clone the linked hash set object.

The clone method returns a shallow copy of this linked hash set object.

Output

Important Note:

Above given all three approaches create a shallow copy of the LinkedHashSet object. That means only the element references are copied, not the actual objects. That is why it is called a shallow copy, not a deep copy or deep clone.

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

Output

How to merge two LinkedHashSet objects (append one LinkedHashSet to another)?

We can use the addAll method to merge two LinkedHashSet objects or append elements of one LinkedHashSet object to another LinkedHashSet object.

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

Output

As we can see from the output, all the elements of the lhSetColors2 linked hash set object were appended to the lhSetColors1 object. Please also note that the element “yellow” was not appended when we merged the two because it was already present in the set object.

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

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

References:
Java 8 LinkedHashSet

About the author

Leave a Reply

Your email address will not be published.