Features Behind LinkedHashSet

The LinkedHashSet is an implementation of a Set Collection in Java. The Set collections are known for storing no-duplicates. The LinkedHashSet is a modified version of Java HashSet. Hence LinkedHashSet extends HashSet. The HashSet is a unique, unordered, and unsorted implementation of the Set collection.

It internally uses the Hash Table and Linked List. Hence it provides a predictable iteration order. In other words, it iterates the records in the order of insertion. Unlike HashSet, the LinkedHashSet maintains a double linked list to store the records.

The Set Collections in Java are Unique. Hence, being a Set implementation, LinkedHashSets are also unique collections. Also, It allows you to insert one and only one null value.

Features of LinkedHashSet

Let’s quickly go over major features of LinkedHashSet.

  • LinkedHashSet is an implementation of Set Collections and stores unique data.
  • The order of insertion is preserved. Hence elements are returned in the same order.
  • TreeSets are Sorted Collections. However, LinkedHashSets are not.
  • Can contain one and only one null element.
  • The elements are stored in a form of the double linked list.
  • The add, remove and contains operations are constant in time.
  • The operations are not synchronized. Therefore you need to handle the synchronization on your own.
  • The Iterator is fail-fast. In other words, if the set is modified once the iterator is open, iterator throws an exception (ConcurrentModificationException).

When to Use LinkedHashSet

LinkedHashSets are combinations of an ArrayList and a HashSet. Because they preserve order like an ArrayList and they allow unique elements like HashSet.

Because of this, you can use them in many scenarios where you want to deduplicate records without changing their sequence. For example, you want to extract a list of website visitors. Where some users might have visited multiple times. Also, you want to maintain the order in which they visited the website.

If you use LinkedHashSet or any collection for that matter, you should first know the data and also the way you want to use that data. In other words, if you don’t bother about the order or sorting of data and just concerned about uniqueness, you should use HashSet. HashSet is faster than LinkedHashSet. Because they don’t have to maintain an extra layer of Double Linked List.

Similarly, if you want records to be maintained in a certain order but don’t want Sorting then LinkedHashSet is best. Because TreeSets have to maintain extra overheads of the tree structure.

 

Related blog:

Java Linkedlist example program