Java – LinkedHashSet class with examples

In this article, we will discuss LinkedHashSet class – one of the Set implemented classes in detail

1. Key points about LinkedHashSet:

  • LinkedHashSet is exactly same as that of HashSet
  • but it preserves insertion-order

2. LinkedHashSet:

  • LinkedHashSet is implementation class of Set interface (i.e.; LinkedHashSet implements Set)
  • This is introduced in Java 1.4 version
  • LinkedHashSet uses combination of LinkedList & hashtable to store element/objects
  • Duplicate element/objects are NOT allowed
  • If duplicate value is added again and again, there won’t be any compile-time or runtime errors
  • Simply add(object); method returns false for already containing object inside LinkedHashSet
  • At any time, LinkedHashSet contains only unique element/objects
  • Insertion-order is maintained
  • While iterating through LinkedHashSet, we will get items as per insertion-order
  • Allows NULL insertion but maximum of only one NULL value
  • Without generics, LinkedHashSet allows to insert any type of objects;
  • with generics, it is type-bounded (except, if we take Object as type within angle brackets)
  • LinkedHashSet is non-synchronized
  • Present in java.util package and extends java.util.HashSet implements java.util.Set interface
  • Also, implements java.lang.Cloneable, java.io.Serializable marker interfaces which provides special ability to LinkedHashSet (provided by JVM at run time) like,
  • java.lang.Cloneable: to create a duplicate object or to clone an object
  • java.io.Serializable: to transfer objects across network
16-LinkedHashSet-interace-in-java

Source: Team BenchResources.Net

3. LinkedHashSet constructors:

3.1 LinkedHashSet hs = new LinkedHashSet();

  • creates an empty LinkedHashSet object of size 16
  • with default fill ratio 0.75

3.2 LinkedHashSet hs = new LinkedHashSet(int initialCapacity);

  • creates an empty LinkedHashSet object of specified size (or initial capacity)
  • with default fill ratio 0.75

3.3 LinkedHashSet hs = new LinkedHashSet(int initialCapacity, float loadFactor);

  • creates an empty LinkedHashSet object of specified size (or initial capacity)
  • and specified fill ratio (for example 0.85)

3.4 LinkedHashSet hs = new LinkedHashSet(Collection c);

  • created an equivalent LinkedHashSet object for the specified collection
  • it is basically used for inter-conversion between collection objects

4. Fill ratio (or Load factor)

  • Fill ratio is also known as Load factor
  • This factor determines when to increase the size of LinkedHashSet automatically
  • For example, for the 1st two constructors the default load factor is 75 –> which means after filling 75 % of LinkedHashSet, new LinkedHashSet of bigger size will be created
  • For 3rd constructor, programmer can define load factor while creating LinkedHashSet object. If programmer define it to be 0.95, then after filling 95% of LinkedHashSet, size of LinkedHashSet will be increased automatically
  • The value of Load factor should be in between 0 to 1.0

5. LinkedHashSet examples:

LinkedHashSetAddAndRemove.java

package in.bench.resources.java.collection;

import java.util.LinkedHashSet;
import java.util.Iterator;

public class LinkedHashSetAddAndRemove {

	public static void main(String[] args) {

		// creating LinkedHashSet object of type String
		LinkedHashSet<String> lhs = new LinkedHashSet<String>();

		// adding elements to LinkedHashSet object
		lhs.add("Sundar Pichai");
		lhs.add("Satya Nadella");
		lhs.add("Shiv Nadar");
		lhs.add("Shantanu Narayen");
		lhs.add("Sundar Pichai"); // adding duplicate element
		lhs.add("Francisco D’Souza");

		// adding null element to LinkedHashSet lhs
		lhs.add(null);
		lhs.add(null); // 2nd null is added, lhs will have one NULL

		// creating Iterator reference
		Iterator<String> ceo = lhs.iterator();

		System.out.println("Iterating using Iterator\n");

		// iterating using while loop
		while (ceo.hasNext()){
			System.out.println(ceo.next());
		}

		System.out.println("\n\nprinting inside square brackets []");
		System.out.println(lhs);

	}
}

Output:

Iterating using Iterator

Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen
Francisco D’Souza
null

printing inside square brackets []
[Sundar Pichai, Satya Nadella, Shiv Nadar, Shantanu Narayen,
Francisco D’Souza, null]

Q) Difference between HashSet and LinkedHashSet ?

  • The main difference between HashSet and LinkedHashSet is insertion-order
  • HashSet doesn’t maintain insertion-order and print values in random-order while iterating
  • whereas LinkedHashSet maintains insertion-order as seen in above example
  • Note: All methods of HashSet/LinkedHashSet is non-synchronized

Q) How to make LinkedHashSet synchronized ?

  • LinkedHashSet can be easily converted into synchronized LinkedHashSet
  • using utility method synchronizedSet(lhs); of java.util.Collections class
Set set = Collections.synchronizedSet(lhs);

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - HashSet v/s LinkedHashSet
Java - HashSet class with examples