Table of Contents
- LinkedHashSet class is the hash table and linked list implementation of the Set interface, with predictable iteration order.
- It maintains a doubly linked list to maintain the order of elements.
- LinkedHashSet iterator returns elements in the order they were inserted, so the elements are iterated in the insertion-order.
- The iteration order is not affected if an element is re-inserted into the LinkedHashSet.
- It’s useful when we want a Set that maintains insertion-order for iteration, but doesn’t want to add the extra overhead associated with the TreeSet.
There are four constructors to create LinkedHashSet instance.
- LinkedHashSet(): creates an empty linked hash set with the default initial capacity (16) and load factor (0.75).
- LinkedHashSet(int initialCapacity): creates a new, empty linked hash set with the specified initial capacity and the default load factor (0.75). It throws the IllegalArgumentException if the initial capacity is less than 0.
- LinkedHashSet(int initialCapacity, float loadFactor): creates an empty LinkedHashSet with the given initial capacity and load factor. It throws IllegalArgumentException if the initial capacity is less than zero, or if the load factor is nonpositive.
- LinkedHashSet(Collection<? extends E> c): creates a new linked hash set with the same elements as the specified collection. It throws NullPointerException if the given collection is null.
A simple example to show that LinkedHashSet iterator returns elements in the order of insertion. The same is not true for the HashSet.
HashSet<String> hs = new HashSet<>(); hs.add("a"); hs.add("i"); hs.add("u"); hs.add("e"); hs.add("o"); System.out.println(hs); hs.forEach(System.out::println); LinkedHashSet<String> lhs = new LinkedHashSet<>(); lhs.add("a"); lhs.add("i"); lhs.add("u"); lhs.add("e"); lhs.add("o"); System.out.println(lhs); lhs.forEach(System.out::println);
[a, u, e, i, o] a u e i o [a, i, u, e, o] a i u e o
- LinkedHashSet iterator return elements in the insertion order. HashSet iterator doesn’t maintain any order.
- LinkedHashSet performance is slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity.
If you are looking for a Set implementation where the elements are iterated in the order of insertion, use LinkedHashSet. It saves the extra performance cost associated with the TreeSet.
Reference: LinkedHashSet API Docs