HashSet v/s LinkedHashSet

In this article, we will discuss difference between HashSet and LinkedHashSet classes in detail i.e.; HashSet v/s LinkedHashSet

HashSet v/s LinkedHashSet:

HashSet LinkedHashSet
Uses hashtable to store element/objects

(actually HashMap instance)

Uses combination of hashtable + LinkedList to store element/objects
Doesn’t maintain insertion order

i.e.; while iterating through HashSet, we will get items in random-order

Since, it uses doubly-linked list to store elements, maintains insertion-order
This is introduced in the original collection framework in Java 1.2 version This is introduced in Java 1.4 version

When to use HashSet ?

  • HashSet stores unique elements using hashing technique
  • So, search operation is faster
  • So, if business requirement is to store unique elements for faster search operation or more number of search operation without concerning insertion-order
  • Then, HashSet is the very apt choice

When to use LinkedHashSet ?

  • This is exactly same as that of HashSet, but underlying data structure to hold items is different
  • It uses doubly-linked list which allows to hold items as per insertion-order
  • So, if business requirement is to store unique elements for faster search operation or more number of search operation concerning/maintaining insertion-order
  • Then, LinkedHashSet is the very apt choice which maintains insertion-order
  • So while iterating through LinkedHashSet, we will get items as per insertion order (as against random in HashSet)

 

Set Program using HashSet and LinkedHashSet :

SetExample.java

package in.bench.resources.collection;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

public class SetExample {

	public static void main(String[] args) {

		// 1. Creating HashSet object
		Set<String> hashSet = new HashSet<String>();

		// add few elements
		hashSet.add("Vijay");
		hashSet.add("Ajith");
		hashSet.add("Vikram");
		hashSet.add("Suriya");

		System.out.println("Displaying HashSet elements"
				+ " in Random-order : \n");
		for(String actor : hashSet) {
			System.out.println(actor);
		}

		// 2. Creating HashSet object
		Set<String> linkedHashSet = new LinkedHashSet<String>();

		// add few elements
		linkedHashSet.add("Sharukh");
		linkedHashSet.add("Akshay");
		linkedHashSet.add("Saif");
		linkedHashSet.add("Salman");

		System.out.println("\nDisplaying LinkedHashSet elements"
				+ " as per Insertion-order : \n");
		for(String actor : linkedHashSet) {
			System.out.println(actor);
		}
	}
}

Output:

Displaying HashSet elements in Random-order : 

Ajith
Vijay
Suriya
Vikram

Displaying LinkedHashSet elements as per Insertion-order : 

Sharukh
Akshay
Saif
Salman

 

References:

 

Happy Coding !!
Happy Learning !!

SortedSet interface
LinkedHashSet class