LinkedHashSet in Java

 

  • LinkedHashSet is a class which extends HashSet class and implements Set, Cloneable, Serializable interface.
  • LinkedHashSet doesn’t allow duplicate elements.
  • It uses node representation to store the elements.
  • We can have null in LinkedHashSet.
  • It maintains insertion order.
  • LinkedHashSet elements can be iterated through Iterator and for-each loop only, it can’t be accessed using ListIterator and Enumeration interface.
  • LinkedHashSet methods are not synchronized.

Example –

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

public class LinkedHashSetExample {
	public static void main(String[] args) {
		Set<String> linkedHashSetObj = new LinkedHashSet();
		linkedHashSetObj.add("ram");
		linkedHashSetObj.add("mohan");
		linkedHashSetObj.add("sohan");
		linkedHashSetObj.add("ram");
		linkedHashSetObj.add("ram");
		System.out.println(linkedHashSetObj);
	}
}

Output – [ram, mohan, sohan]