2

HashMap always returns values ordered by keys although documentation says it's not guaranteed:

public static void main(String[] args) {
    HashMap<Integer, String> map = new HashMap<>();
    map.put(8, "B");
    map.put(7, "C");
    map.put(5, "A");
    map.put(10, "Z");
    map.put(3, "D");
    map.put(1, "B");
    System.out.println(map);
    printCollection(map);
}

private static void printCollection(Map<Integer, String> map) {
    for(Map.Entry<Integer, String> pair : map.entrySet()){
        System.out.println(pair.getKey() + " " + pair.getValue());
    }
}

Output: {1=B, 3=D, 5=A, 7=C, 8=B, 10=Z}

1 B
3 D
5 A
7 C
8 B
10 Z
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Alex Smoke
  • 619
  • 1
  • 8
  • 18

3 Answers3

2

"Not guaranteed" doesn't mean "never". Probably you just had luck, and you should not rely on that.

If you want an ordered HashMap you should use LinkedHashMap.

Ozwizard
  • 99
  • 1
  • 5
  • It's not luck, there is a definitive explanation why he is getting this result (it is not random in this case) – Tunaki Sep 25 '15 at 09:55
  • 1
    It is luck by definition: he's getting an ordered list while that property is not guaranteed. Obviously the inner-workings of the map are not "magic", there is a specific implementation (i know that), but from his point of view should be irrelevant. – Ozwizard Sep 25 '15 at 10:06
1

You are testing with a very small set of key. The default size of the HashMap is 16, so it is storing them in order and sending back.

Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).

The hashcode for Integer is value itself, so they will be stored in the each of the bucket.

Try this simple code and see the output:

Map<Integer, String> map = new HashMap<>();
for (int i = 0; i<100; i++) {
  map.put(i, "a");
}
for (Map.Entry entry : map.entrySet())
   System.out.print(entry.getKey() + "  ");

Output:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 16 19 18 21 20 23 22 25 24 27 26 29 28 31 30 34 35 32 33 38 39 36 37 42 43 40 41 46 47 44 45 51 50 49 48 55 54 53 52 59 58 57 56 63 62 61 60 68 69 70 71 64 65 66 67 76 77 78 79 72 73 74 75 85 84 87 86 81 80 83 82 93 92 95 94 89 88 91 90 98 99 96 97

Till 15 keys are sorted, but then they start spreading randomly.

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
0

Yes. You are getting in this case. But not guaranteed as doc said. Order will change if you keep adding and removing overtime.

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307