To create a HashSet, you first need to import the Java.util.HashSet package. After importing this package, you can now create the Java HashSet using the following syntax:
HashSet HashSet = new HashSet<>(); |
We operate on a HashSet using the following methods:
add()- adds the specified set elements
addAll()- adds all the elements of the specified set collection
iterator()- enables accessing of the Set elements
remove()- The specified elements are removed from the HashSet
removeAll()- Removes all elements from the set
addAll()- Performs union between two sets.
import java.util.HashSet; public class HashSetExamples { public static void main(String[] args) { HashSet HS = new HashSet<>(); // Using add() method HS.add(8); HS.add(9); HS.add(10); System.out.println("First HashSet: " + HS); HashSet HS2 = new HashSet<>(); // Using addAll() method HS2.addAll(HS); HS2.add(11); System.out.println("Second HashSet: " + HS2); } } |
Output:
First HashSet : [8, 9, 10]
Second HashSet : [8, 9, 10, 11]
Article Contributed By :
|
|
|
|
150 Views |