Search code examples
javacollectionshashsetlinkedhashset

Why doesn't LinkedHashSet always retain order?


Set<String> stringSet = new HashSet<String>();

will not retain order obviously

Set<String> linkedHastSet = new LinkedHashSet<String>();

while reading elements from the above set it should retain order but in some times it does not ? am I wrong in my observation or I am missing something ?


Solution

  • Only LinkedHashSet guarantees predictable order

    From jdoc:

    Hash table and linked list implementation of the Set interface, with predictable iteration order