Does Hashmap autosort?

前端 未结 3 1146
有刺的猬
有刺的猬 2021-02-15 14:33

This is my hashmap :

HashMap hashMapTest = new HashMap();

and I insert Date.getTime() into this

3条回答
  •  终归单人心
    2021-02-15 15:27

    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 hashMap = new HashMap();
    Map treeMap = new TreeMap();
    Map linkedHashMap = new LinkedHashMap();
    // 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}
    

提交回复
热议问题