JAVA中关于map集合常见的几种实现接口

关于实现map有一下几种接口:

第一种:HashMap:Map的典型实现,元素是无序且不可重复,这里的元素指的是key

第二种:LinkedHashMap:以插入的次序作为排序状态,其他的和HashMap一致

第二种:第三种:TreeMap:元素处于排序状态,可以使用自然排序(升序)也可以使用自定义排序,但key的类型必须一致,不然无法进行比较

/**
     * 第一种:HashMap:Map的典型实现,元素是无序且不可重复,这里的元素指的是key
     * 
    */
   public static void testHashMap(){
        Map<Object,Object> hashMap = new HashMap<Object, Object>();
        hashMap.put(1, 1);
        hashMap.put(3, "word");
        hashMap.put(2, "helloWord");
        //通过key获取value
        System.out.println(hashMap.get(1));         //1
        System.out.println(hashMap.get("helloWord"));     //null
        System.out.println(hashMap);      //{1=1, 2=helloWord, 3=word}
    }

/**
     * 第二种:LinkedHashMap:以插入的次序作为排序状态,其他的和HashMap一致
     * 
    */
    public static void testLinkedHashMap(){
        LinkedHashMap<Integer,String> lkMap = new LinkedHashMap<Integer,String>();
        lkMap.put(1, "H");
        lkMap.put(3, "E");
        lkMap.put(4, "L");
        lkMap.put(2, "O");
        System.out.println(lkMap);//结果:{1=H, 3=E, 4=L, 2=O}
    }

/**
     * 第三种:TreeMap:元素处于排序状态,可以使用自然排序(升序)也可以使用自定义排序,但key的类型必须一致,不然无法进行比较
     * 
    */
    public static void testTreeMap(){
        //HashMap<Integer,Object> hm = new HashMap<Integer,Object>();
        TreeMap<Integer,Object> tmp = new TreeMap<Integer,Object>(new MyComparatorBigtoSmall());
        tmp.put(4, "肆");
        tmp.put(1, "壹");
        tmp.put(5, "伍");
        tmp.put(3, "三");
        tmp.put(2, "贰");
        //System.out.println(tmp);//默认排序结果:{1=壹, 2=贰, 3=三, 4=肆, 5=伍}
        System.out.println(tmp);//修改为比较器排序(升序){5=伍, 4=肆, 3=三, 2=贰, 1=壹}
    }

//自定义TreeMap排序方法    比较器排序    
    class MyComparatorBigtoSmall implements Comparator<Integer>{

        @Override
        public int compare(Integer o1, Integer o2) {
            // TODO Auto-generated method stub
            return o2-o1;
        }
    }

猜你喜欢

转载自blog.csdn.net/Websphere_zxf/article/details/86416364