We have seen that in 'HashSet' the insertion order was not maintained. i.e. Say we have inserted the elements A, B and C one after the other in a HashSet. But while displaying the contents of the HashSet, the output might be 'B C A' or 'C B A' and not 'A B C'.
Now, to maintain this order 'LinkedHashSet' comes to rescue. In 'LinkedHashSet', insertion order of the 'Set' is maintained.
LinkedHashSet() : Creates a LinkedHashSet with initial capacity 16 and load factor 0.75.
LinkedHashSet(int initialCapacity) : Creates a HashSet with a custom initial capacity.
HashSet(int initialCapacity, float LoadFactor) : Creates a HashSet with a custom initial capacity and custom Load Factor.
1) We have created three Strings s1, s2 & s3.
2) Then we have created a LinkedHashSet() using the below format.
3) Next we have added Strings s1,s2 & s3 using the add() method.
4) When we have printed the values of the LinkedHashSet, we have seen the names are exactly printed in the order they were inserted.
i.e. We have inserted Sham, Paul and then John.
And when we printed the names. Sham, Paul and then John was printed.
This is because the names are inserted serially at the HashSet().
Since, 'Paul' is stored in s2. We have removed 'Paul' by using the remove() method.