4

I want to know if my HashMap collection will be always on the same order

        Map<Integer, Long> map = new HashMap<Integer, Long>(0);

        for(Integer key : users) {
            map.put( key , (long) 0 );
        }

        for( ... ){
            ...
            if( ... ) ){
                map.put( t.get(key) , map.get(key) + 1);
            }
        }

I send this collection to javascript with ajax

                    $.each( jsonData[i].totalMap , function(key, value) {
                        rows.push(value);
                    });

will have always the same order of the element of the Map as i put them in my controller ?

Hayi
  • 6,972
  • 26
  • 80
  • 139
  • Can you elaborate on your use case? If you need to rely on this behaviour but you do not require a specific ordering, I suspect your design may be flawed in some way. Besides the answers posted, there are also `SortedMap`s – Simon Fischer Mar 25 '15 at 10:50
  • for safety i will use `LinkedHashMap` because the same order when i Initialize my map in controller I want it when i iterate over my map in javascript code – Hayi Mar 25 '15 at 11:01

2 Answers2

4

If you use a LinkedHashMap, the order will be kept (i.e., by default, the keys will always be iterated in the same order they were inserted into the Map).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks man :) for safety i will use `LinkedHashMap` because the same order when i Initialize my map in controller I want it when i iterate over my map in `javascript` code. – Hayi Mar 25 '15 at 10:56
1

If the keys and values are always the same, the map size is the same, and the HashMap is initialized in the same way, then yes. However for guaranteed iteration order, use a LinkedHashMap.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • On a given system. :). The same instance can have a different hashcode on a different machine – TheLostMind Mar 25 '15 at 10:49
  • Exactly, on a given VM/version. – Kayaman Mar 25 '15 at 10:50
  • @Kayaman - Nope. For some classes, you will typically get different hashcodes each time you run the application. (Same hardware, JVM version, etc.) – Stephen C Mar 25 '15 at 10:52
  • @StephenC True, but here the Integer/Long would be deterministic on a given system. Not that I would ever trust or recommend others to trust that ;) – Kayaman Mar 25 '15 at 10:54
  • thanks man for your help for safety i will use `LinkedHashMap` because the same order when i Initialize my map in controller I want it when i iterate over my map in `javascript` code. – Hayi Mar 25 '15 at 10:57
  • For the `Integer` class the hashcode is specified to be the same as the wrapped value. You *can* trust that. But `Integer` is unusual in this respect. – Stephen C Mar 25 '15 at 11:05