Is LinkedHashMap LIFO or FIFO in nature? If my map is of the form:
map.put(1,"one");
map.put(2,"two");
what would be the order if I was to iterate on the map using keyset??
EDIT: I think I did actually confuse two different concepts. Let me rephrase the question. What would be the order in which I encounter the quantities using entryset?Thanks for pointing that out btw. I do not intend to remove any entry.
In a linked hash map the elements in the backing doubly-linked list are added at the end (clearly: for preserving iteration order), but can be removed from any part in the list as the elements get removed from the map, it's incorrect to label the backing list (and by extension: the map) as LIFO or FIFO, it's neither - there's no concept of removal order in a map, and consequently no removal order can be assumed for the backing list in a linked hash map.
What a linked hash map does guarantee is that iterating over its contents (be it: the keys or the entries) will occur in the same order in which the elements were inserted in the map; from the documentation:
This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
EDIT :
Regarding the last edit to the question, a LinkedHashMap
guarantees that the iteration order of the keySet()
will be the same order in which the elements were inserted: 1, 2
for the example in the question. This has nothing to do with FIFO/LIFO, those concepts deal with the order in which elements are removed from a data structure, and they're not related with the iteration order after inserting elements.