HashSet Class:
It extends AbstractList class and implements List interface. It uses hashing technique to store data. It contains only unique elements. We can use HashSet class by importing java.util package.
Example:
import java.util.*;
public class HashDemo {
public static void main(String args[]) {
// create a hash set
HashSet hash = new HashSet();
// add elements to the hash set using add() function
hash.add("B");
hash.add("A");
hash.add("D");
hash.add("E");
hash.add("C");
hash.add("F");
System.out.println(hash); //printing the hash collection
}
}
Output:
[A, B, C, D, E, F]
List can have duplicate elements but Set contains unique elements only.
Some of the mostly used methods of HashSet :
add(): used to add a element to the set
clear(): Removes all element from the set.
remove() :Removes the specified element from the set if it is present.
0 Comment(s)