Java HashSet Class
HashSet class extends AbstractSet and implements the set interface . A set is a collection that contains no duplicate elements, and whose elements are in no particular order. In HashSet , hash table is used for storage. A hash table stores information by using a mechanism called hashing. In simple, hashing is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties. Hash function should return the same hash code each and every time, when function is applied on same or equal objects.
//Creates a hash set and initializes the capacity.
HashSet(capacity)
HashSet(capacity,fillRatio)


The following Java program illustrates several of the methods supported by this HashSet collection Framework
import java.util.*;
class TestClass
{
public static void main (String[] args) throws java.lang.Exception
{
//create a HashSet Object
HashSet days=new HashSet();
// add elements to the HashSet
days.add("Sunday");
days.add("Monday");
days.add("Tuesday");
days.add("Wednesday");
days.add("Thursday");
days.add("Friday");
days.add("Saturday");
//Iterate through HashSet
Iterator itr=days.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
//remove a single entry from hashset
days.remove("Monday");
System.out.println(days);
//search in Hashset
if(days.contains("Saturday"))
System.out.println("Item Found");
else
System.out.println("Item Not Found");
//Remove all items from Hashset
days.clear();
//Size of the hashset
System.out.println("Size of the HashSet: "+days.size());
}
}
Related Topics