Add elements in HashSet
We can use add() method of HashSet to add elements to HashSet collection
boolean add(Object obj)
It adds the element obj to the Set.
Example
- import java.util.HashSet;
- public class HashSetAddExample {
- public static void main(String args[]) {
- HashSet<String> hs = new HashSet<String>();
- hs.add("java");
- hs.add("c");
- hs.add("c++");
- System.out.println(hs);
- }
- }
import java.util.HashSet; public class HashSetAddExample { public static void main(String args[]) { HashSet<String> hs = new HashSet<String>(); hs.add("java"); hs.add("c"); hs.add("c++"); System.out.println(hs); } }
Using addAll() method
We can also add another HashSet to existing HashSet using addAll() method
Example :
- import java.util.HashSet;
- public class HashSetAddAllExample {
- public static void main(String args[]) {
- HashSet<String> hs = new HashSet<String>();
- HashSet<String> hs1 = new HashSet<String>();
- hs.add("java");
- hs.add("c");
- hs.add("c++");
- hs1.add("python");
- hs1.add("oracle");
- hs.addAll(hs1);
- System.out.println(hs);
- }
- }
import java.util.HashSet; public class HashSetAddAllExample { public static void main(String args[]) { HashSet<String> hs = new HashSet<String>(); HashSet<String> hs1 = new HashSet<String>(); hs.add("java"); hs.add("c"); hs.add("c++"); hs1.add("python"); hs1.add("oracle"); hs.addAll(hs1); System.out.println(hs); } }
Note : Using addAll() , we can also add elements of another collection like list to HashSet