HashSet Example Java Program

Definition

A set can't have any duplicate elements in it. Additionally, the set has no set order. As such, elements can't be found by index. HashSet uses a hash table.

Syntax

HashSet  Variable_name = new HashSet();

HashSet Example Program

import java.util.*;

class HashSetExample{
	public static void main(String[] args){
		HashSet hs=new HashSet();
		hs.add("d");
		hs.add("c");
		hs.add("b");
		hs.add("a");
		hs.add("c");
		System.out.println("Hashset is "+hs);
		System.out.println("Size of Hashset is "+hs.size());
	}
}

Sample Output

Output is:
Hashset is [d, b, c, a]
Size of Hashset is 4