LinkedHashMap,HashMap,TreeMap

package com.test;

import java.util.*;

/**
 * @author ****
 * @create 2017-07-10 20:28
 */
public class LinkedHashMapAndHashMap {

    public static void main(String[] args) {
        System.out.println("LinkedHashMap测试开始");
        linkedHashMapTest();
        System.out.println("HashMap测试开始");
        hashMapTest();
        System.out.println("TreeMap测试开始");
        treeMapTest();
    }

    private static void linkedHashMapTest() {
        Map<Integer, String> linkedHashMap = new LinkedHashMap<Integer, String>();
        linkedHashMap.put(9, "植物");
        linkedHashMap.put(7, "动物");
        linkedHashMap.put(5, "微生物");
        linkedHashMap.put(null,null);
        linkedHashMap.put(null,"null");
        for (Map.Entry<Integer, String> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }

    private static void hashMapTest() {
        Map<Integer, String> hashMap = new HashMap<Integer, String>();
        Collections.synchronizedMap(hashMap);
        hashMap.put(9, "植物");
        hashMap.put(7, "动物");
        hashMap.put(5, "微生物");
        hashMap.put(null,null);
        hashMap.put(null,"null");
        Iterator iterator = hashMap.keySet().iterator();
        while (iterator.hasNext()) {
            Object o = iterator.next();
            System.out.println( o + ":" + hashMap.get(o));
        }
    }

    private static void treeMapTest() {
        Map<Integer, String> treeMap = new TreeMap<Integer, String>();
        treeMap.put(9, "植物");
        treeMap.put(7, "动物");
        treeMap.put(5, "微生物");
        for(Iterator iterator = treeMap.keySet().iterator();iterator.hasNext();) {
            Object key = iterator.next();
            System.out.println(key + ":" + treeMap.get(key));
        }
    }
}

从Map中按插入数据顺序取数据的时候用LinkedHashMap,HashMap和TreeMap都会默认排序。

posted @ 2017-07-10 21:02  ゞ清茶℡  阅读(179)  评论(0编辑  收藏  举报