1. 程式人生 > >JAVA中關於map集合常見的幾種實現介面

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;
        }
    }