Does Hashmap autosort?

2020-06-17 05:41发布

问题:

This is my hashmap :

HashMap<Long, Day> hashMapTest = new HashMap<Long, Day>();

and I insert Date.getTime() into this hashmap like :

Date start = new Date(vonDatum.getTime());

for (int i = 0; i < tagediff; i++)
  {
    Day day= new Day(start);
    this.mitarbeiterTagHashMap.put(start.getTime(), day);
    CalendarUtil.addDaysToDate(start, 1);
  }

The strange thing is when I call the hashmap with, the order is completely an other and the keys doesnt fit to the insertion :

for (Long name : hashMapTest.keySet())
 {
     Window.alert(name + ": " + hashMapTest.get(name));
 }

回答1:

The strange thing is when i call the hashmap with, the order is completly an other and the keys doesnt fit to the insertion :

HashMap does NOT maintain the order of insertion but there is an alternative called LinkedHashMap that maintains the insertion order. Or if you want the keys to be sorted in natural order(using keys compareTo method) then you may go for TreeMap.



回答2:

Following are 4 common implementation of Map interface in Java,

HashMap: No ordering & No preservation of insertion order on keys/values

LinkedHashMap: Preserves the insertion order

TreeMap: Ordered by the key

HashTable: Unlike HashMap, it is synchronized

Refer here for better understanding with examples.



回答3:

No, HashMaps don't sort their keys automatically.

You want a TreeMap for sorting the keys, or a LinkedHashMap to retain the insertion order.

Here's an example:

long l0 = 0l;
long l1 = 1l;
Map<Long, String> hashMap = new HashMap<Long, String>();
Map<Long, String> treeMap = new TreeMap<Long, String>();
Map<Long, String> linkedHashMap = new LinkedHashMap<Long, String>();
// does not guarantee key order 1, 0
hashMap.put(l1, null);
hashMap.put(l0, null);
// guarantees key order 0, 1
treeMap.put(l1,  null);
treeMap.put(l0,  null);
// guarantees key order 1, 0
linkedHashMap.put(l1,  null);
linkedHashMap.put(l0,  null);
System.out.printf("HashMap: %s%nTreeMap: %s%nLinkedHashMap: %s%n", hashMap, treeMap, linkedHashMap);

Output

HashMap: {0=null, 1=null}
TreeMap: {0=null, 1=null}
LinkedHashMap: {1=null, 0=null}