HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(5,a);
map.put(4,b);
map.put(3,c);
map.put(2,d);
map.put(1,e);
System.out.println(map);
Why the result is equal {1=e, 2=d, 3=c, 4=b, 5=a}?
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(5,a);
map.put(4,b);
map.put(3,c);
map.put(2,d);
map.put(1,e);
System.out.println(map);
Why the result is equal {1=e, 2=d, 3=c, 4=b, 5=a}?
Java HashMap
doesn't keep any order. API says
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
From HashMap
's javadoc:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
A LinkedHashMap
would suffice for ordering by insertion order, and a TreeMap
may be used when order through a key's comparator is needed.