HashSet Concept Simplified In Java


HashSet Concept Simplified In Java:

HashSet: The Hashset class extends the AbstractSet class and implements the Set interface.The AbstractSet class itself extends the AbstractCollection class.The HashSet class is used to create a collection and store it in a Hashtable.Each collection refers to a unique value called hashcode.The hashcode is used as an index to associate with the object which is stored in the hash table.This type of storing information in a hash table is called hashing. It is important to note that the HashSet does not gurantee teh order of its elements.Elements may be in any order.
Hashset is introduced in 1.2V in java.

The features are..

  • Underlying data structure is HashTable. 
  • Insertion order is not preserved. It is based on hashcode of objects.
  • Null insertion is possible but only once.
  • Heterogeneous objects are allowed.
  • Duplicate objects are not allowed.[ If tried to insert a duplicate object, Java will not throw any Compile time error or run time exception,simply the add method will return false.]
  • HashSet implements serializable and cloneable interface.
  • It does not implement RandomAccess Interface

HashSet is best when we do search operation in application. The process is very fast.

The structure of HashSet is given as:

public HashSet();//constructs an empty HashSet
public HashSet(Collection c);//Initialize the HashSet using the elements present in the collection.
public HashSet(int capacity);//Initialize the capacity of the HashSet.
public HashSet(int capacity,float fillratio);//initializes the capacity and fill ratio of the HashSet.
See also  How to work with Thread in Java

Importance of fillratio:

The value of the fill ratio ranges from 0.0 to 1.0. This value is used to set the initial size of the HashSet.If the number of elements is greater than the capacity of the HashSet,the size of the HashSet is expanded automatically by multiplying the capacity with the fill ratio.The default value of the fill ratio is .75.The hashSet class inherits the methods of its parent classes and the methods of the implemented interfaces.

An Example:

import java.util.*;
public class HahSetTest{
public static void main(String []args){
HashSet hs=new HashSet();
System.out.println("The content of the HashSet is "+hs);

The output of the code:
$javac HahSetTest.java
Note: HahSetTest.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$java -Xmx128M -Xms16M HahSetTest
The content of the HashSet is [A, B, C]

Share and Enjoy !

Leave a Reply

Your email address will not be published. Required fields are marked *