What is HashSet

What is HashSet

Answer: Java HashSet is a class which extends AbstractSet implements Set interface. For storage of collections it uses hash table also HashSet is generic class and has below declaration:

class HashSet<E>

Where E generic which specifies type of objects that set will be holding

Below are the constructor of HashSet

  • HashSet( )
  • HashSet(Collection<? extends E> c)
  • HashSet(int capacity) – Defualt capacity is 16
  • HashSet(int capacity, float fillRatio) – fillRatio must be between 0.0 and 1.0 and for constructor where there is no fill ratio it .75.

Probably you will be familiar that hash table stores information using technique that is called
hashing. In hashing technique, value of key has code used to determine its unique value and used to index data that will be stored. It is internal technique where the hash code of the key performed automatically put value in it. Advantage of hashing technique is that it permits execution time of the operation add( ), contains( ), remove( ), and size( ) to always constant for very large sets.

Important: HashSet don’t keep elements in its order, because hash code of the key use index and store element in the bucket and hash code of the key doesn’t comes in sorted order. If requirement is to keep element in sorted order then go for TreeSet.

Below is example of HashSet:

package com.javahonk.hashsettest;

import java.util.HashSet;

public class HashSetTest {

	public static void main(String args[]) {

	HashSet<String> hs = new HashSet<String>();
	// Add elements
	hs.add("Java");
	hs.add("Honk");
	hs.add("Test");	
	System.out.println(hs);
	}
}

 

Output:

What is HashSet

 

Leave a Reply

Your email address will not be published. Required fields are marked *