Map 的 key、value 是否允许为null

Map的key和value是否允许null?

直接写程序验证一下:

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author robin
 */
public class MyTest {


    public static void main(String[] args) {
        Map<Object, Object> m1 = new HashMap<>();
        Map<Object, Object> m2 = new TreeMap<>();
        Map<Object, Object> m3 = new Hashtable<>();
        Map<Object, Object> m4 = new ConcurrentHashMap<>();


        try {
            m1.put("zzz", null);
        } catch (Exception e) {
            System.out.println("m1-a:" + e.getMessage());
        }
        try {
            m1.put(null, null);
        } catch (Exception e) {
            System.out.println("m1-b:" + e.getMessage());
        }
        try {
            m2.put("zzz", null);
        } catch (Exception e) {
            System.out.println("m2-a:" + e.getMessage());
        }
        try {
            m2.put(null, null);
        } catch (Exception e) {
            System.out.println("m2-b:" + e.getMessage());
        }
        try {
            m3.put("zzz", null);
        } catch (Exception e) {
            System.out.println("m3-a:" + e.getMessage());
        }
        try {
            m3.put(null, null);
        } catch (Exception e) {
            System.out.println("m3-b:" + e.getMessage());
        }
        try {
            m4.put("zzz", null);
        } catch (Exception e) {
            System.out.println("m4-a:" + e.getMessage());
        }
        try {
            m4.put(null, null);
        } catch (Exception e) {
            System.out.println("m4-b:" + e.getMessage());
        }
    }


}

执行结果:

 

m2-b:null
m3-a:null
m3-b:null
m4-a:null
m4-b:null

结论如下表:

image

posted @ 2019-01-02 22:39  robin·张  阅读(27584)  评论(3编辑  收藏  举报