Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Tuesday, October 14, 2014

HashSet in collection framework


HashSet

HashSet is the direct subclass of Set interface , HashSet doesn’t allow duplicates element insertion and insertion order is not preserved.

  1.  Underlined data structure is HashTable.
  2. HashSet doesn't allow duplicates.
  3.  Insertion order is not preserved.
  4.  Null insertion is allowed.
  5.  Heterogeneous objects are allowed. 
  6. Implements Serializable and clonable interfaces.

Constructor in HashSet

HashSet hs=new HashSet();  // creates an empty HashSet


HashSet hs=new HashSet(int initialCapacity); 

//Creates and empty HashSet with passed initialCapacity and default load factor 0.75.

HashSet hs=new HashSet(Collection c); 

//Creates a HashSet representation of Passed collection object.

HashSet hs=new HashSet(int initialCapacity, float loadFactor); 

//creates an empty HashSet with given initialCapacity and given loadFactor.

Example:

import java.util.*;
class HashSetDemo 
{
 public static void main(String[] args) 
 {
  HashSet hs=new HashSet();
  hs.add(10);
  hs.add(20);
  hs.add(30);
  hs.add(10);
  hs.add("Hello");
  hs.add(null);
  hs.add(new HashSetDemo());
  System.out.println(hs);
  System.out.println(hs.remove(30)); /*removes the passes argument object from 
           the HashSet and returns true, false otherwise.*/
  System.out.println("Total number of elements in the HashSet "+hs.size());
  hs.clear(); //clear the entire HashSet 
  System.out.println(hs);
  
 }
}

Output:



No comments: