Tutorials

Java Collection Framework


Java LinkedHashSet


LinkedHashSet implements Set interface and extends HashSet class. It is part of java.util package.

 

Declaration of LinkedHashSet class


public class LinkedHashSet extends HashSet implements Set, Cloneable, Serializable

 

Key features of LinkedHashSet

  • LinkedHashSet is almost similar to HashSet except that it maintains the insertion order. If we use LinkedHashSet then it will return element in same order in which they were inserted.
  • To maintain insertion order, LinkedHashSet maintains a doubly-linked list running through all its entries.
  • LinkedHashSet is non-Synchronized. In order to Synchronize it, use Collections.synchronizedSet()
  • Iterator returned by LinkedHashSet are fail-fast*.

*Fail-fast – If a set is modified at any time after the creation of iterator, except iterator’s own remove method, the iterator will throw ConcurrentModificationException.

Create LinkedHashSet in java

Now let’s look at the ways in which we can create LinkedHashSet in java.

  • LinkedHashSet mySet = new LinkedHashSet();
  • LinkedHashSet mySet = new LinkedHashSet (Collection c);
  • LinkedHashSet mySet = new LinkedHashSet (int initialCapacity);
  • LinkedHashSet mySet = new LinkedHashSet (int initialCapacity, float LoadFactor);

Simple example on LinkedHashSet


package javaRadarLinkedHashSet;

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

public class SimpleLHS {

       public static void main(String[] args) {

             //create Array List
             LinkedHashSet javaRadarSet = new LinkedHashSet();

             //Add elements to ArrayList
             javaRadarSet.add("Java");
             javaRadarSet.add("Java");
             javaRadarSet.add("Spring");
             javaRadarSet.add("Hibernate");
             javaRadarSet.add("EJB");

             //creating iterator to traverse over javaRadarSet

             Iterator setIterator = javaRadarSet.iterator();

             while(setIterator.hasNext()){

             System.out.println(setIterator.next());

             }

     }

}

OUTPUT:

Java
Spring
Hibernate
EJB

 

Difference

  • HashSet vs LinkedHashSet
  • LinkedHashSet vs TreeSet

 

 



Please Share this page
Views : 50