«Back to Home

Core Java

Topics

HashSet Class In Java

HashSet class
 
In Java, HashSet class uses hashtable to store the elements. It extends AbstractSet class and implements Set interface. It contains unique elements only, which means it doesn’t allow duplicates. If we try to add a duplicate element in HashSet, the old value would be overwritten. It doesn’t maintain any order and the elements would be returned in any random order. HashSet class allows the null values. However, if we insert more than one nulls, it would still return only one null value. It is non-synchronized.
 
List can contain the duplicate elements whereas Set contains the unique elements only.
 
Constructors of HashSet Class

HashSet( )

This constructor is used to construct a default HashSet.
 
HashSet(Collection c)

This constructor is used to initialize the hash set, using the elements of the collection c.
 
HashSet(int capacity)

This constructor is used to initialize the capacity of the HashSet to the given integer value capacity. The capacity grows automatically as the elements are added to the HashSet.
 
HashSet(int capacity, float fillRatio)

This constructor is used to initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments.
 
Methods of HashSet Class

boolean add(Object o)

This method is used to add the particular element to the set, if it is not already present.
 
void clear()

This method is used to remove all the elements from the set.
 
Object clone()

This method is used to return a shallow copy of the HashSet instance as the elements themselves are not cloned.
 
boolean contains(Object o)

This method is used to return true, if the set contains the specified element.
 
boolean isEmpty()

This method is used to return true, if the set contains no elements.
 
Iterator iterator()

This method is used to return an iterator over the elements in the set.
 
boolean remove(Object o)

This method is used to remove the specified element from the set, if it is present.
 
int size()

This method is used to return the number of elements in the set.
 
Let’s see an example, given below.
 
Code
  1. import java.util.*;  
  2. public class CollectionsExample {  
  3.     public static void main(String args[]) {  
  4.         HashSet < String > h = new HashSet < String > ();  
  5.         h.add("Marria");  
  6.         h.add("Harry");  
  7.         h.add("James");  
  8.         h.add("Harry");  
  9.         Iterator < String > i = h.iterator();  
  10.         while (i.hasNext()) {  
  11.             System.out.println(i.next());  
  12.         }  
  13.     }  
  14. }  
31 
 
Output

32
 
Summary

Thus, we learnt that Java HashSet class uses hashtable to store the elements. It extends AbstractSet class and implements Set interface. It contains the unique elements only and we also learnt its important methods in Java.