Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
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]
Advertisements
