Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Hashmap autosort?

Tags:

java

date

hashmap

This is my hashmap :

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

and I insert Date.getTime() into this hashmap like :

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 strange thing is when I call the hashmap with, the order is completely an other and the keys doesnt fit to the insertion :

for (Long name : hashMapTest.keySet())
 {
     Window.alert(name + ": " + hashMapTest.get(name));
 }
like image 536
Domi Avatar asked Oct 10 '14 10:10

Domi


People also ask

Does HashMap guarantee default ordering?

(The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Does HashMap store keys in sorted order?

The map is sorted according to the natural ordering of its keys.

Are HashMaps sorted?

HashMap is not meant to keep entries in sorted order, but if you have to sort HashMap based upon keys or values, you can do that in Java. Sorting HashMap on keys is quite easy, all you need to do is to create a TreeMap by copying entries from HashMap.

Does HashMap store in ascending order?

The simple answer is no, a hash map doesn't have an "order". It is all determined based on how the object is hashed. For a number you could see some ordering, but that is purely based on the hashCode() method of the object that is the key for the put().


1 Answers

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.

like image 114
Juned Ahsan Avatar answered Sep 19 '22 22:09

Juned Ahsan