Is the order guaranteed for the return of keys and values from a LinkedHashMap object?
The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the
TreeMap
class, make specific guarantees as to their order; others, like theHashMap
class, do not.
-- Map
This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
-- LinkedHashMap
So, yes, keySet()
, values()
, and entrySet()
(the three collection views mentioned) return values in the order the internal linked list uses. And yes, the JavaDoc for Map
and LinkedHashMap
guarantee it.
That is the point of this class, after all.
Looking at the source, it looks like it does. keySet()
, values()
, and entrySet()
all use the same entry iterator internally.
Don't get confused with LinkedHashMap.keySet()
and LinkedHashMap.entrySet()
returning Set and hence it should not guarantee ordering !
Set
is an interface with HashSet
,TreeSet
etc beings its implementations. The HashSet
implementation of Set
interface does not guarantees ordering. But TreeSet
does. Also LinkedHashSet
does.
Therefore it depends on how Set
has been implemented in LinkedHashMap
to know whether the returning Set reference will guarantee ordering or not.
I went through the source code of LinkedHashMap
, it looks like this:
private final class KeySet extends AbstractSet<K> {...}
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {...}
Thus LinkedHashMap/HashMap has its own implementation of Set
i.e. KeySet
. Thus don't confuse this with HashSet
.
Also, the order is maintained by how the elements are inserted into the bucket. Look at the addEntry(..)
method of LinkedHashMap
and compare it with that of HashMap
which highlights the main difference between HashMap
and LinkedHashMap
.