- Java Data Structures Resources
- Java Data Structures - Quick Guide
- Java Data Structures - Resources
- Java Data Structures - Discussion
Java Data Structures - Adding two Sets
The Set interface provides a method named addAll() (inherited from Collection interface) using this method you can add the contents of one set to another set.
Example
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class AddingTwoSets {
public static void main(String args[]) {
Set set1 = new HashSet();
set1.add(100);
set1.add(501);
set1.add(302);
set1.add(420);
System.out.println("Contents of set1 are: ");
System.out.println(set1);
Set set2 = new HashSet();
set2.add(200);
set2.add(630);
set2.add(987);
set2.add(665);
System.out.println("Contents of set2 are: ");
System.out.println(set2);
set1.addAll(set2);
System.out.println("Contents of set1 after addition: ");
System.out.println(set1);
}
}
Output
Contents of set1 are: [100, 420, 501, 302] Contents of set2 are: [630, 200, 665, 987] Contents of set1 after addition: [100, 420, 501, 630, 200, 665, 987, 302]
Advertisements