HashMap should be unsorted but still sorts according to key

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

    It's a coincidence (not really, rather it has to do with the hashing algorithm).

    Try adding

    newHashMap.put(-5, "Fifth");
    

    as last.

    Output will be

    Key: 0
    Value: Second
    Key: 1
    Value: Fourth
    Key: 2
    Value: First
    Key: 3
    Value: Third
    Key: -5
    Value: Fifth
    

    The javadoc specifically says

    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.

提交回复
热议问题