HashMap should be unsorted but still sorts according to key

前端 未结 9 1998
余生分开走
余生分开走 2021-01-06 06:08

According to these:

  1. http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
  2. Difference between HashMap, LinkedHashMap and TreeMap
  3. jav
9条回答
  •  别那么骄傲
    2021-01-06 06:42

    Like every one is saying (AND is right about) is that you should assume that the keys in an HashMap are not sorted. Now they LOOK sorted in your case for two simple reasons:

    1 - You are using Integer as a key: The HashMap use the hashCode() method of the Object class of Java to find the index in the underlying array it uses to store the Entry instances (what contains your values and keys in the HashMap). It just so happen that the hashcode of an Integer is its own value.

    2 - You are not setting the initial size of the HashMap and thus are using its default initial size (which is 16). So until you add a key below 0 or above 16 (included) you will see the keys stored in order. Since the HashMap gets the index by doing

    int index = newKey.hashCode() % this.capacity;
    

    Later on HashMap might increase the capacity of its underlying array if you insert a lot key-value pairs (how and when it decides to do that is very interesting if you are into algo and data structure study), so you might end up in a situation in which your Integer keys might look sorted again, but they actually are not intentionally sorted.

    Btw if your keys are going to be Integers and you can estimate the maximum key value you are going to have I'd suggest to directly use an array. Access is faster and the memory used will be the same or slightly less.

提交回复
热议问题