HashSet


HashSet available since Java 1.2

HashSet implements following Interfaces:
  • Serializable
  • Cloneable
  • Iterable<E>
  • Collection<E>
  • Set<E>

HashSet has four constructors:
  • HashSet() 
  • HashSet(Collection c) 
  • HashSet(int initialCapacity) 
  • HashSet(int initialCapacity, int loadFactor) 

Characteristics:
  • The underlying data structure used for HashSet is HashTable.
  • Default initial capacity of HashSet is 16.
  • Default loat factor of HashSet is 0.75.
  • HashSet does not maintain order.
  • HashSet doen not allow duplicate elements.
  • Once the total elements in the HashSet is reach upto the load factor then the capacity of HashSet increased automatically.
  • Elements in the HashSet are stored using the HashCode value of the element.
  • HashCode is unique value for each element calculated using the hashing algorithm.
  • HashSet allows null element.

Example:

import java.util.*;
class HashSetFlight {
    public static void main(String args[]) {
      
        HashSet<String> hs = new HashSet<String>();
        hs.add("A");


        hs.add("A"); 

       // adding duplicate return false

        hs.add("C");
        hs.add("D");


        hs.add(null); 

       // null allowed

        System.out.println(hs);
    }
}


Output:
[null, D, A, C]