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所谓的有序并不是按照数字顺序,而是字典顺序

 

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