1
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}?

user3114474
  • 75
  • 1
  • 1
  • 9

2 Answers2

3

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.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
  • "So, try some times, you will get different order of printing the content." It's also not guaranteed that it will be different. Are you sure that bogus orderings aren't returned deterministically? – nanofarad May 23 '14 at 11:48
  • @hexafraction : Not sure, I guess it, removed those lines – Abimaran Kugathasan May 23 '14 at 11:49
0

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.

nanofarad
  • 40,330
  • 4
  • 86
  • 117