Java LinkedHashSet is an implementation of hash table and linked list of the Set interface. Unlike HashSet, LinkedHashSet maintains the order of its elements. That means it returns the elements in the same order they were inserted into it.

Another difference between HashSet and LinkedHashSet is that it maintains doubly linked list internally to link all of its elements. So it guarantees to maintain the insertion order of the elements.

Since HashSet does not maintain the order of the elements and if there is such requirement, you can create a LinkedHashSet object from the existing set object using LinkedHashSet constructor which accepts a Set object argument like given below

LinkedHashSet linkedSet = new LinkedHashSet(existingHashSetObject);

The LinkedHashSet provides all the optional operations defined by the Set interface. Like HashSet, LinkedHashSet also allows null elements. The LinkedHashSet provides constant time performance for the basic operations like add, contains and remove.

Generally, the performance of the LinkedHashSet is slightly less than HashSet due to an added overhead of maintaining the internal doubly linked list. However, when it comes to the iterating over the Set, LinkedHashSet needs time proportional to the size of Set, while HashSet needs time proportional to its capacity which is likely to be more expensive than LinkedHashSet.

Like HashSet, LinkedHashSet is also not synchronized. That means if multiple threads are simultaneously accessing the LinkedHashSet object and modifying it, the code must do the synchronization explicitly. You can also get synchronized set instance from the existing LinkedHashSet object using the synchronizedSet method of Collections class.

Below given are some of the Java LinkedHashSet examples which shows how to use LinkedHashSet in Java.

Java LinkedHashSet Examples

Sorry, there are no posts found on this page. Feel free to contact website administrator regarding this issue.