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