Copy HashSet in Java Example (append)

This example shows how to copy HashSet to another HashSet in Java. The example also shows how to append one HashSet to another using the addAll method.

How to copy HashSet to another HashSet in Java?

There are several ways using which you can copy one HashSet to another as given below.

1. Using constructor

You can use the below given HashSet constructor to copy the set object.

This HashSet constructor accepts the Collection object and creates a new HashSet object containing all the elements of the specified collection.

Output

2. Using the addAll method

We can also use the addAll method of the HashSet class to copy.

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

Output

3. Using the clone method

We can also use the clone method of the HashSet class to clone the HashSet object.

The clone method creates a shallow copy of the HashSet object and returns it.

Output

Important Note:

All of the above given approaches only copies the element object reference only. None of the methods given above will deep copy the HashSet object. In order words, only the reference to the element objects are copied, not the actual objects.

The copied HashSet elements still point to the original object. That means, if you change the actual element object, the change will be reflected in both the HashSet objects. In order to understand this, let’s have a look at the below example.

Output

As we can see from the output, the change in one of the objects was reflected in both the HashSet objects.

How to append one HashSet to another in Java?

We can use the same addAll method to append elements of one HashSet to another.

Output

Important Note: Unlike ArrayList or LinkedList, the HashSet class does not guarantee the element order returned by the Iterator so appended elements may come before the elements that were already present in the set when you iterate the HashSet.

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

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

References:
Java 8 HashSet

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *