HashMap should be unsorted but still sorts according to key

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

    It's pure coincidence. Sometimes it appears to be sorted, but keep adding keys and the dream will shatter.

    I wrote this little program:

    import java.util.Map;
    import java.util.HashMap;
    
    class MapTest {
    
        public static void main(String[] args){
            int count = Integer.parseInt(args[0]);
            Map map = new HashMap();
            for (int i = 0; i < count; i++) map.put(i, i);
            System.out.println(map);
        }
    
    }
    

    When running java MapTest 20, I get the following output (line-wrapped for readability):

    {0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10, 11=11, 12=12, 13=13, 
    14=14, 15=15, 17=17, 16=16, 19=19, 18=18}
    

    It's simply a property of the implementation of HashMap that Integers added sequentially (and starting at 0) at first seem to be ordered.

提交回复
热议问题