Java LinkedHashSet Class

Category: Java   Tags: Java, Java Collection, Java Set Interface, Java LinkedHashSet Class

The LinkedHashSet class extends HashSet and implements the Set interface. LinkedHashSet is a generic class that has this declaration:

                                    public class LinkedHashSet<E>
                                    extends HashSet<E>
                                    implements Set<E>, Cloneable, Serializable

Here, E specifies the type of object that this set will contain. It maintains a doubly-linked list running through all of its entries. Because of this the elements will be returned in the order in which they were inserted.


public LinkedHashSet()
It will create a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).
public LinkedHashSet(int capacity)
It will create an empty LinkedHashSet with an initial capacity specified by capacity and default load factor (0.75).
public LinkedHashSet(int capacity, float loadFactor)
It will create an empty LinkedHashSet with an initial capacity specified by capacity and load factor loadFactor.
public LinkedHashSet(Collection<? extends E> c)
It creates a LinkedHashSet containing the elements of the specified collection c.

It is very important not to set the initial capacity too high or the load factor too low; if iteration performance is important.

LinkedHashSet is not synchronized. Therefore if multiple thread is accessing the set then it must synchronized externally. You can check out this post about synchronization. You can use Collections.synchronizedSet also to synchronize the LinkedHashSet:

                                    Set set = Collections.synchronizedSet(new LinkedHashSet());

The returned iterator of this class are fail-fast i.e during iterating the LinkedHashSet if you do any modification, it will throw ConcurrentModificationException exception. Here is one LinkedHashSet example:


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

                            public class LinkedHashSetDemoExample {

                                public static void main(String[] args) {
                                    LinkedHashSet<Integer> set = new LinkedHashSet<>();
                                    System.out.println("Size: " + set.size());

                                    //Iterate the LinkedHashSet
                                    System.out.println("LinkedHashSet iteration: ");
                                    Iterator<Integer> iterator = set.iterator();
                                    while (iterator.hasNext()) {
                                        Integer element =;



                            Size: 3
                            LinkedHashSet iteration:

As you can see that LinkedHashSet keeps the order in which data was inserted.