This is my hashmap :
HashMap hashMapTest = new HashMap();
and I insert Date.getTime()
into this
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.
No, HashMap
s 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}
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.