Home » Core Java » LinkedHashSet in Java

LinkedHashSet in Java

LinkedHashSet & its feature ::
1.  LinkedHashSet class is an important class of Collection framework.
2.  LinkedHashSet extends generic AbstractSet.
3.  LinkedHashSet implements generic Set, cloneable and java.io.Serializable interface.
4.  LinkedHashSet internally crates a HashMap with initial capacity 16 and load factor of 0.75.LinkedHashSet stores values in the key of the HashMap.So LinkedHashSet has always have unique elements stored.If you try to add duplicate element LinkedHashSet replaces the old value with new value.
5.  LinkedHashSet is unsynchronized i.e. it is not thread safe.But, it can be made synchronized explicitly like below

5.  LinkedHashSet can accept any element including multiple null values.
7.  LinkedHashSet uses Iterator interface to traverse the elements.While traversing the elements using iterator if the      structure of the LinkedHashSet is modified using add or remove method ,iterator will throw ConcurrentModificationException.So iterators for LinkedHashSet are fail-fast..While iterating you can add new elements without getting ConcurrentModificationException.
8.LinkedHashSet class provides all of the optional Set operations, and permits null elements. Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just 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.

Sample Program ::

Output ::

Now let us see an example of ConcurrentModificationException.In the below program while iterating the LinkedHashSet,i am modifying the structure of the LinkedHashSet by removing an element.So I am getting ConcurrentModificationException.
Example of ConcurrentModificationException ::

Output ::

Leave a comment

Your email address will not be published. Required fields are marked *

sixteen + fourteen =