Java -HashSet class

  • This class implements the Set interface.
  • HashSet  uses hashtable to store the elements.
  • HashSet doesn’t maintain any order, the elements would be returned in any random order.
  • HashSet  contains unique elements only.
  • HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.
  • HashSet allows null values however if you insert more than one nulls it would still return only one null value.
  • HashSet is non-synchronized.

 

class HashSet<T>

We can create HashSet for storing String type elements as follows:

HashSet<String> hs=new HashSet<String> ();

We can create HashSet for storing Integer type elements as follows:

HashSet<Integer> hs=new HashSet<Integer> ();

 

HashSet contains the following constructors:

  • HashSet (): It is constructors default hash set.
  • HashSet (Collection c): It initializes hash set by using elements of c.
  • HashSet (int capacity): It creates HashSet with initial capacity , default capacity  of HashSet is 16.
  • HashSet (int capacity, float fillRatio): it initializes capacity and fillRatio to grow the capacity after certain elements inserted.

 

HashSet Example

  1. import java.util.*;
  2. class MyHashSetDeo{
  3.  public static void main(String args[]){
  4.   HashSet<String> hs=new HashSet<String>();
  5.   hs.add(“A”);
  6.   hs.add(“B”);
  7.   hs.add(“C”);
  8.   hs.add(“D”);
  9.   Iterator<String> itr=hs.iterator();
  10.   while(itr.hasNext()){
  11.    System.out.println(itr.next());
  12.   }
  13.  }
  14. }
Output:
       A
       B
       C
       D

HashSet Methods:

  1. boolean add(Element  e): It adds the element e to the list.
  2. void clear(): It removes all the elements from the list.
  3. Object clone(): This method returns a shallow copy of the HashSet.
  4. 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.
  5. boolean isEmpty(): Returns true if there is no element present in the Set.
  6. int size(): It gives the number of elements of a Set.
  7. boolean(Object o): It removes the specified Object o from the Set.

HashSet Example

import java.util.HashSet;
public class MyHashSetDemo1 {
   public static void main(String args[]) {
      // HashSet declaration
      HashSet<String> hset =new HashSet<String>();
      // Adding elements to the HashSet
      hset.add("A");
      hset.add("M");
      hset.add("G");
      hset.add("O");
      hset.add("B");
      //Addition of duplicate elements
      hset.add("A");
      hset.add("M");
      //Addition of null values
      hset.add(null);
      hset.add(null);

      //Displaying HashSet elements
      System.out.println(hset);
    }
}

Output:

[null, M, G, A, O, B]
 

Leave a comment