- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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