Copy all the elements from one set to another in Java


Use the clone() method to copy all elements from one set to another.

First HashSet −

HashSet <String> set = new HashSet <String>();
set.add("One");
set.add("Two");

Create another set and clone first set into the second −

HashSet <String> newSet = new HashSet <String>();

Copy (clone) all elements to the second set −

newSet = (HashSet)set.clone();

The following is an example to copy all elements from one set to another −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet <String> set = new HashSet <String>();
      HashSet <String> newSet = new HashSet <String>();
      set.add("One");
      set.add("Two");
      System.out.println("Hash Set "+ set);
      newSet = (HashSet)set.clone();
      System.out.println("New Hash Set: "+ newSet);
   }
}

Output

Hash Set: [One, Two]
New Hash Set: [One, Two]

Updated on: 30-Jul-2019

881 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements