HashMap does not provide values ​​in the order in which they were added

I put values ​​in a HashMap. But when I read the values ​​from this HashMap; I DO NOT get these values ​​in the ORDER to which I added them. Can anyone help me out?

+5
source share
4 answers

HashMap does not guarantee preservation of the insertion order.

Use LinkedHashMapif you need such a guarantee.

This implementation differs from HashMap in that it maintains a double-linked list that goes through all its entries. This linked list defines the iteration order, which is usually the order in which the keys were inserted into the map (insertion order).

+6
source

From the Java documentation:

; , , .

+4

HashMap does not guarantee the order in which items are returned. With LinkedHashMap you can receive items in the order in which they were added; With TreeMap, you can get them sorted.

+1
source

This is stated in javadocs for HashMap

http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

This class makes no guarantees regarding the order of the card; in particular, it does not guarantee that order will remain constant over time.

0
source

All Articles