HashSet in Java

HashSet in Java

HashSet in Java implements the Set interface and is part of the Collections interface. It is contained in the java.util package. The HashSet works with the help of a hash table in the background which is an instance of a HashMap. HashSets are unordered collections and allow an element to be null.

Features of the HashSet

  • Implements the Set Interface
  • Uses a hash table which is an instance of a Hash Map.
  • As HashSet is a subclass of the Set interface, you cannot have duplicate elements.
  • The order of insertion of objects is not maintained in HashSets.
  • Elements can be null in a HashSet.

Declaration Syntax

public class HashSet extends Abstract Set <E> class and implements Set <E>, Cloneable, Serializable

Components of a HashSet

  • Initial Capacity – Defining an initial capacity is equivalent to defining the number of buckets that will be created. Buckets are part of the underlying HashSet that is used to configure a HashSet. When the full capacity is approached, the buckets automatically increase as part of the HashSet algorithm.
  • Load Factor – The load factor determines at what phase of the HashSet will the buckets be increased. It can be mathematically defined as follows:

Example

import java.util.*;
class HashSetDemo
{
public static void main(String[] args)
{
 HashSet<String> h = new HashSet<String>();

h.add ( "India" );
h.add ( "Australia" );
h.add ( "South Africa" );
h.add ( "India" );

System.out.println ( h );
System.out.println ( "List contains India or not:" + h.contains ( "India" ) );

h.remove ("Australia");
System.out.println ("List after removing Australia:" + h);

System.out.println ("Iterating over list:");
Iterator<String> i = h.iterator();
while (i.hasNext())
System.out.println (i.next());
}
}

 

OUTPUT

[South Africa, Australia, India] List contains India or not: True
List after removing Australia: [South Africa, India] Iterating over list:
South Aftrica
India

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.