Search code examples
javahashmapputelement

HashMap messes up the order of its own elements


Simple as the title, I searched it up already, and I didn't find anything about this issue, I'm pretty sure I just misunderstood how a HashMap works with its own elements. Super-simplest code:

HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("first key", 1);
    map.put("second key", 2);
    map.put("third key", 3);

    System.out.println(map.toString());

What does the println() method show? It shows this:

{third key=3, first key=1, second key=2}

I tough the HashMap stored elements as the programmer put them in. Even a sorting would sort would place these elements as I put them in origin. I tried changing the words and similar things happen(only the positions changed, but they were "wrong" anyway). :/ Do you know why?

Thanks in advance :/

EDIT: Rohit Jain is actually the first that answered me as comment, and you guys told me about LinkedHashMap, so you helped me to solve, thank you very much :)


Solution

  • There are different Map types, giving different guarantees about their key order (see this).

    HashMap: Undefined ordering of its elements.

    LinkedHashMap: Order defined by insertion.

    TreeMap: Order defined by the compareTo() method of their elements.

    So, HashMap makes no guarantee about it's iteration order. Once you insert another element, you will get a different ordering. From what you described a LinkedHashMap might be what you need.