TreeMap中的键,值能否为null? |
您所在的位置:网站首页 › 是否允许null值 › TreeMap中的键,值能否为null? |
今天想到一个问题,HashMap中键值都可以为null,ConcurrentHashMap,HashTable中键值不可以为null, 以上参考:https://blog.csdn.net/gagewang1/article/details/54971965 那么TreeMap呢? 我们一起来看一下吧。 1. 首先, 先分析简单的, value是否能为null? public static void main(String[] args) { TreeMap treeMap = new TreeMap(); treeMap.put("1",1); treeMap.put("2",null); System.out.println(treeMap.get("2")); }结果: nullvalue是可以为null的。 2. 再来看看 key 是否能是 null public static void main(String[] args) { TreeMap treeMap = new TreeMap(); treeMap.put("1",1); treeMap.put(null,null); System.out.println(treeMap.get("2")); }结果: Exception in thread "main" java.lang.NullPointerException at java.util.TreeMap.put(TreeMap.java:563) at com.crazy_june.test_treemap.main(test_treemap.java:9)出错,空指针异常 NullPointerException。 3.TreeMap是需要我们实现Comparator接口的,上面的例子中String是自己实现了Comparator接口的,我们自己来实现一个Comparator看看。 public static void main(String[] args) { TreeMap treeMap = new TreeMap(new Comparator() { @Override public int compare(String o1, String o2) { if(o1==null){ return 1; }else { return o2.charAt(0)-o1.charAt(0); } } }); treeMap.put("1",1); treeMap.put(null,12); treeMap.put("2",2); System.out.println(treeMap.get(null)); }结果: null可以看到,结果并不能取出来,我们试试遍历entry看看: for(Map.Entry entry:treeMap.entrySet()){ System.out.println(entry.getKey()+":"+entry.getValue()); }结果: 2:2 1:1 null:12结果看到了吧。 4. 我们来总结一下: 当未实现 Comparator 接口时,key 不可以为null,否则抛 NullPointerException 异常; 当实现 Comparator 接口时,若未对 null 情况进行判断,则可能抛 NullPointerException 异常。如果针对null情况实现了,可以存入,但是却不能正常使用get()访问,只能通过遍历去访问。 现在我们知道了,如果去使用TreeMap的时候,还是需要键为null的情况的。 现在晚上12点10分了,回宿舍睡觉了,明天再战,加油! |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |