Does Hashmap autosort?

前端 未结 3 1158
有刺的猬
有刺的猬 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:17

    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.

    0 讨论(0)
  • 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<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}
    
    0 讨论(0)
  • 2021-02-15 15:38

    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.

    0 讨论(0)
提交回复
热议问题