JAVA++:HashMap無序?TreeMap有序?

書上說HashMap是無序的,TreeMap是有序的(有序無序是針對key的),但是實際去敲的時候發現不是這樣,有時HashMap是有序的,有時TreeMap是無序的。

於是就做了以下測試來探究:

          //第一組測試:HashMap和TreeMap的key都是String類型的
        Map<String, Integer> hashMap = new HashMap<String, Integer>();
        hashMap.put("8", 3);
        hashMap.put("9", 2);
        hashMap.put("10", 6);
        hashMap.put("11", 2);
        hashMap.put("12", 6);
        System.out.println("第一組測試:HashMap和TreeMap的key都是String類型的");
        System.out.println("HashMap:");
        System.out.println(hashMap);

        Map<String, Integer> treeMap = new TreeMap<String, Integer>();
        treeMap.put("8", 399);
        treeMap.put("9", 67);
        treeMap.put("10", 2);
        treeMap.put("11", 67);
        treeMap.put("12", 2);
        System.out.println("TreeMap:");
        System.out.println(treeMap);
        System.out.println();

        //第二組測試:HashMap和TreeMap的key都是Integer類型的
        Map<Integer, Integer> hashMap2 = new HashMap<Integer, Integer>();
        hashMap2.put(9, 67);
        hashMap2.put(10, 2);
        hashMap2.put(8, 399);
        hashMap2.put(11, 67);
        hashMap2.put(12, 2);
        System.out.println("第二組測試:HashMap和TreeMap的key都是Integer類型的");
        System.out.println("HashMap:");
        System.out.println(hashMap2);

        Map<Integer, Integer> treeMap2 = new TreeMap<Integer, Integer>();
        treeMap2.put(9, 67);
        treeMap2.put(10, 2);
        treeMap2.put(8, 399);
        treeMap2.put(11, 67);
        treeMap2.put(12, 2);
        System.out.println("TreeMap:");
        System.out.println(treeMap2);
        System.out.println();

        //第三組測試:HashMap和TreeMap的key都是String類型的,但是都是英文字母
        Map<String, Integer> hashMap3 = new HashMap<String, Integer>();
        hashMap3.put("apple", 1);
        hashMap3.put("orange", 2);
        hashMap3.put("pear", 3);
        System.out.println("第三組測試:HashMap和TreeMap的key都是String類型的,但是都是英文字母");
        System.out.println("HashMap:");
        System.out.println(hashMap3);

        Map<String, Integer> treeMap3 = new TreeMap<String, Integer>();
        treeMap3.put("apple", 1);
        treeMap3.put("orange", 2);
        treeMap3.put("pear", 3);
        System.out.println("TreeMap:");
        System.out.println(treeMap3);

運行結果:

第一組測試:HashMap和TreeMap的key都是String類型的
HashMap:
{11=2, 12=6, 8=3, 9=2, 10=6}
TreeMap:
{10=2, 11=67, 12=2, 8=399, 9=67}

第二組測試:HashMap和TreeMap的key都是Integer類型的
HashMap:
{8=399, 9=67, 10=2, 11=67, 12=2}
TreeMap:
{8=399, 9=67, 10=2, 11=67, 12=2}

第三組測試:HashMap和TreeMap的key都是String類型的,但是都是英文字母
HashMap:
{orange=2, apple=1, pear=3}
TreeMap:
{apple=1, orange=2, pear=3}

通過測試可以總結出:

當key值是Integer類型時,HashMap和TreeMap都是“有序”的;
當key值是String類型的數字時,HashMap和TreeMap都是“無序”的;
當key值是String類型的字母時,HashMap是“無序”的,TreeMap是有序的。

後來又去查了一下TreeMap是按照什麼來排序的,結果:TreeMap按照key的字典順序來排序(升序)
這樣就對上了,之前感覺當key值是String類型的數字時,HashMap和TreeMap都是“無序”的,是因爲如果按照數字排序的話確實是無序的,但是TreeMap所謂的有序並不是按照數字順序,而是字典順序

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章