HashMap should be unsorted but still sorts according to key

前端 未结 9 1997
余生分开走
余生分开走 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:53

    You should not infer too much! Just because three or four numbers appear sorted, it doesn't mean they have been sorted.

    The hash code of a positive int is usually just that int, so if all your keys are lower than the length of the internal array the Map maintains, they may appear sorted.

    Try with really big values, and you'll see that the apparing order vanishes. For example, use

    100,200,300,100001, 100002, 10003, 999123456, 888777666, ....

    0 讨论(0)
  • 2021-01-06 06:58

    Since no answer really utilized looking at the Java source, I will do so! :)

    When you call the put() function, the internal hash function uses the hashCode of the object, to generate the hashing index. [put() source]

    The hash() function simply ensures that hashCodes that differ only by constant multiples at each bit position have a bounded number of collisions [use Google to see why that is the case].

    Things just coincidentally worked here. That is about it.

    0 讨论(0)
  • 2021-01-06 07:03

    Mine is an educated guess, but the reason is likely to be the fact that the default hashCode method uses the memory location. The memory location of small Integers (and your keys are autoboxed into Integer) are most likely fixed: it would be nonesense to have Integer.valueOf(1) return a different memory location on multiple calls. Finally, most likely these fixed memory locations are in the ascending order. This would explain this coincidence, but well, one would need to dig into the implementation of Integer and HashMap to prove this.

    Correction: in case of Integer "A hash code value for this object, equal to the primitive int value represented by this Integer object." (JavaDoc). Which, although a different number, confirms the idea.

    0 讨论(0)
提交回复
热议问题