Java – HashSet v/s LinkedHashSet

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

1. HashSet v/s LinkedHashSet:

HashSetLinkedHashSet
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 versionThis is introduced in Java 1.4 version

Q) 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

Q) 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)

2. 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

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - SortedSet interface
Java - LinkedHashSet class with examples