Java HashSet Examples

Java Hashset is implements the Set interface and it is backed by a hash table(actually a HashMap instance). It does not give any guarantees as to the iteration order.It allows null element. It does not allows duplicacy of element.This Class is not synchronized.

Hashset Features In Java

1. HashSet does not maintain any order of iteration order , element can be rreturn any random oder.
2. HashSet does not allow duplicacy of element.
3. Hashset allow one null element .
4. Hashset is non-synchronized.
5. The iterator returned by hashset class is fail-fast which means iterator would throw ConcurrentModificationException
if HashSet has been modified any time after creation of iterator, by any means except iterator’s own remove method.
6. HashSet also implements Searlizable and Cloneable interfaces.

HashSet Hierarchy

It extends AbstractSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.declaration for HashSet class as below.

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{

}

 

hierarchy of linkedList class in java
Hierarchy of linkedList class in java

 

Creating Hashset And Adding elements to it

We can create hashset in java using these constructors .                                                    HashSet() – This constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
HashSet(Collection<? extends E> c) –  it constructs a new set containing the elements in the given collection.
HashSet(int initialCapacity) – It constructs a new, empty set; the backing HashMap instance has the given initial capacity and default load factor (0.75).
HashSet(int initialCapacity, float loadFactor) –  it constructs a new, empty set; the backing HashMap instance has the given initial capacity and the specified load factor.                                              We can add element in hashset using add() method .

add(E e) – It adds the specified element to this set if it is not already present.                                Let’s see how we can create hashset and adding elements to it .

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class HashSetAdd {
	public static void main(String[] args) {
		
		//Constructs a new, empty set
	   HashSet<String>	hashSet = new HashSet<String>();
	   
	   //add element in it 
	   hashSet.add("java");
	   hashSet.add("php");
	   
	   //display the element 
	   System.out.println("element in hashset ="+ hashSet);
	   
	   //create arraylist 
	   List<String> list = new ArrayList<String>();
	   list.add("amit");
	   list.add("shubham");
	   list.add("shivam");
	   
	   //create hashset from collection. Here we will use arraylist
	   HashSet<String>	hashSetFromCollection = new HashSet<String>(list);
	   
	   //display hashset
	   System.out.println("element in hashset ="+ hashSetFromCollection);
		
	}
}

Output :

element in hashset =[java, php]
element in hashset =[shubham, shivam, amit]

Iterating over a HashSet

We can iterate hashSet using different ways. Here will discuss these below ways

  • Iterate over a HashSet using iterator()
  • Iterate over a HashSet using simple for-each loop.
import java.util.HashSet;
import java.util.Iterator;

public class HashSetIterating {
	
	public static void main(String[] args) {
		  
		   //Constructs a new, empty set
		   HashSet<String>	hashSet = new HashSet<String>();
		   
		   //add element in it 
		   hashSet.add("java");
		   hashSet.add("php");
		   hashSet.add("android");
		   
		   System.out.println("====> Iterate HashSet using iterator() ====>");
	       Iterator<String> hashSetIterator = hashSet.iterator();
	       while (hashSetIterator.hasNext()) {
	    	   String element = hashSetIterator.next();
	    	   System.out.println("element is ="+element);
	    	   }
	    System.out.println("====> Iterate HashSet using for for each loop ====>");
           for (String element : hashSet) {
        	System.out.println("element is ="+ element);   
           }
		   
	       }    
	
	   }

Output :

====> Iterate HashSet using iterator() ====>
element is =java
element is =android
element is =php
====> Iterate HashSet using for for each loop ====>
element is =java
element is =android
element is =php

 

How to remove elements from a HashSet ?

We can element from hashset using remove() method. Let’s see this by code below

package com.demo;

import java.util.HashSet;

public class HashSetAdd {
	public static void main(String[] args) {
		
		//Constructs a new, empty set
	   HashSet<String>	hashSet = new HashSet<String>();
	   
	   //add element in it 
	   hashSet.add("java");
	   hashSet.add("php");
	   hashSet.add("android");
	   
	   //display the element 
	   System.out.println("element in hashset ="+ hashSet);
	   
	   //remove php element from hashset
	   hashSet.remove("php");
	   System.out.println("after remove element hashset ="+ hashSet);
	}
}

Output :

element in hashset =[java, android, php]
after remove element hashset =[java, android]

HashSet Methods

  1. add(E e) – This method adds the given element to this set if it is not already present.
  2. clear() – This method removes all of the elements from this set.
  3. clone() – This method returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
  4. contains(Object o) – This method returns true if this set contains the specified element.
  5. isEmpty() – This method returns true if this set contains no elements.
  6. remove(Object o) – This method removes the given element from this set if it is present.
  7. size() – This method returns the number of elements in this set (its cardinality).
  8. spliterator() – It is creates a late-binding and fail-fast Spliterator over the elements in this set.

Leave a Reply

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

27 − 22 =