The HashSet Interface tutorial in Java Collection

The HashSet Interface implements the Set Interface in java collection and store the elements in a hash table. The HashSet Interface does not support duplicate elements like List Interface but allows NULL values for the elements. The empty hash set is created with default initial capacity as 16 and load factor as 0.75 when constructor hashSet() is invoked. The elements inserted in the HashSet are based on the hashcode values and does not follow any element ordering.

HashSet Interface in Java Collection

The HashSet Interface class Hierarchy is given below

java.lang.Object
-> java.util.AbstractCollection<E>
->-> java.util.AbstractSet<E>
->->-> java.util.HashSet<E>

The implemented interfaces by HashSet Interface

Serializable, Cloneable, Iterable<E>, Collection<E>, Set<E>

The HashSet Interface provides the below given constructors

HashSet Constructors HashSet Constructor Description
HashSet()creates a empty HashSet which provides default initial capacity as 16 and load factor as 0.75
HashSet(Collection c)creates a new hash set containing the elements in the specified collection
HashSet(int initialCapacity)creates a empty HashSet with provided initial capacity and load factor as 0.75
HashSet(int initialCapacity, float loadFactor)creates a empty HashSet with provided initial capacity and provided load factor

Methods for HashSet Interface

The HashSet Interface provides the below given methods for implementation

HashSet MethodsHashSet Methods Description
add(E e)add the specified element to the set
clear()removes all elements from the set
clone()returns a shallow copy of the HashSet instance but does not clone the elements
contains(object o)returns true if specified element presents in the set
isEmpty()returns true if no elements in the set
iterator()returns iterator over the elements in the set
remove (object o)remove the specified element if present in the set
size()returns the set size
spliterator()Creates a late-binding and fail-fast Spliterator over the elements in the set

HashSet Example in collection

import java.util.*;  
class FruitsHashSet{  
 public static void main(String args[]){  
  //Create HashSet object as fruits
    HashSet<String> fruits=new HashSet();  
  // Add elements to fruits 
           fruits.add("Apple");    
           fruits.add("Orange");    
           fruits.add("Banana");   
           fruits.add("Gauva");  
           fruits.add("Pears");  
           Iterator<String> itr =fruits.iterator();  
           while(itr.hasNext())  
           {  
                    System.out.println(itr.next());  
           }  
 }  
}  

The HashSet Interface tutorial in Java Collection

Leave a Reply

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

Scroll to top
error: Content is protected !!