LinkedHashMap與HashMap

來源:互聯網
上載者:User

顧名思義LinkedHashMap是比HashMap多了一個鏈表的結構。與HashMap相比LinkedHashMap維護的是一個具有雙重鏈表的 HashMap,LinkedHashMap支援2中排序一種是插入排序,一種是使用排序,最近使用的會移至尾部例如 M1 M2 M3 M4,使用M3後為 M1 M2 M4 M3了,LinkedHashMap輸出時其元素是有順序的,而HashMap輸出時是隨機的,如果Map映射比較複雜而又要求高效率的話,最好使用 LinkedHashMap,但是多線程訪問的話可能會造成不同步,所以要用Collections.synchronizedMap來封裝一下,從而實現同步。其實現一般為:Map<String String> map = Collections.synchronizedMap(new LinkedHashMap(<String String));

 

System.out.println("*************************LinkedHashMap*************");
        Map<Integer, String> map = new LinkedHashMap<Integer, String>();
        map.put(6, "apple");
        map.put(3, "banana");
        map.put(2, "pear");

//        for (Iterator it = map.keySet().iterator(); it.hasNext();) {
//            Object key = it.next();
//            System.out.println(key + "=" + map.get(key));
//        }
        for(Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }

        System.out.println("*************************HashMap*************");
        Map<Integer, String> map1 = new HashMap<Integer, String>();
        map1.put(6, "apple");
        map1.put(3, "banana");
        map1.put(2, "pear");

        for (Iterator it = map1.keySet().iterator(); it.hasNext();) {
            Object key = it.next();
            System.out.println(key + "=" + map1.get(key));
        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.