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
结论如下表:
转载于:https://www.cnblogs.com/amunote/p/10211760.html
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/101227.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...