Self-portrait Hashmap?

This is my hashmap:

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

      

and I insert Date.getTime()

into this hashmap, for example:

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 weird thing is when I call the hashmap with, the order is completely different and the keys are not suitable for insertion:

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

      

+3


source to share


3 answers


The weird thing is when I call a hashmap with, the order is completely different and the keys are not suitable for insertion:



HashMap does NOT support insertion order, but there is an alternative called LinkedHashMap that does support insertion order. Or, if you want the keys to be sorted in natural order (using the compareTo method with keys), you can go to TreeMap .

+6


source


Following are the 4 common implementations of the Map interface in Java,

HashMap : ordering and not keeping insertion order on keys / values

LinkedHashMap : Preserves insertion order



TreeMap : ordered by key

HashTable : Unlike HashMap, it syncs

Refer here for a better understanding with examples.

+4


source


No, HashMap

don't sort your keys automatically.

Sorting keys require TreeMap

or LinkedHashMap

to preserve 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}

      

+2


source







All Articles