Java HashSet

Java HashSet  class

  • The Hashset class in Java implements the set interface, backed by a hash table. And it does not make sure that the order will remain constant over each iteration.
  • It is a collection of items where every item is unique and it is found in the java.util package.
  • Creation of HashSet: Creating a HashSet object called sooks that will store strings:
import java.util.HashSet; // Importing the HashSet class

HashSet<String> sooks = new HashSet<String>();
  • We can add items to it: The HashSet class has many useful methods. For example, to add items to it, use the add() method:
import java.util.HashSet;

public class MyClass 
{
  public static void main(String[] args) 
{
    HashSet<String> sooks = new HashSet<String>();
    sooks.add("Beyond"); //addng Beyond to set
    sooks.add("sookshmas");
    sooks.add("knowing"); // adding knowing to set using method add()
    System.out.println(sooks);
  }
}
  • The above code snippet will give you the output as
    [knowing,Beyond,sookshmas]
  • HashSet methods available are: 
Methods  use

boolean add(Element e) 

It adds the element e to the list.
void clear() It removes all the elements from the list.
Object clone() This method returns a shallow copy of the HashSet.
boolean contains(Object o) It checks whether the specified Object o is present in the list or not. If the object has been found it returns true else false.
boolean isEmpty()  Returns true if there is no element present in the Set.
int size() It gives the number of elements of a Set.
boolean(Object o) It removes the specified Object o from the Set.
  • This Hashset class is non-syncronized and it permits the null element.But it can be synchronized explicitly.For example,
 Set s = Collections.synchronizedSet(new HashSet(...));
  • Hashset doesn't allow duplicates. If we try to add a duplicate element in HashSet, the old value would be overwritten.
  • The iterator returned by this class is fail-fast which means iterator would throw ConcurrentModificationException if HashSet has been modified after creation of iterator, by any means except iterator’s own remove method.
Posted on by