[英]Why does the implementations of Map handle null differently?
Let's take the containsKey(Object key)
as example:我们以containsKey(Object key)
为例:
Lets have a look into the Javadoc for TreeSet:让我们看看 TreeSet 的 Javadoc:
Throws NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys 抛出 NullPointerException - 如果指定的键为 null 并且此映射使用自然排序,或者其比较器不允许空键
Meaning: those two Map implementations really have different semantics.含义:这两个 Map 实现确实具有不同的语义。 Therefore it makes sense that their individual implementations of "Map" methods do work differently.因此,他们对“Map”方法的单独实现确实以不同的方式工作是有道理的。
One key property of TreeSet is the fact that it supports/requires ordering . TreeSet 的一个关键属性是它支持/需要排序。 That doesn't play nicely with null , thus it is "fair" to throw when null is coming in.这与null 效果不佳,因此当null进入时抛出是“公平的”。
Just read the documentation here :只需阅读此处的文档:
Some map implementations have restrictions on the keys and values they may contain.一些地图实现对它们可能包含的键和值有限制。 For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys.例如,有些实现禁止空键和值,有些实现对其键的类型有限制。 Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException.尝试插入不合格的键或值会引发未经检查的异常,通常为 NullPointerException 或 ClassCastException。 Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false;尝试查询不合格的键或值的存在可能会引发异常,或者它可能只是返回 false; some implementations will exhibit the former behavior and some will exhibit the latter.一些实现会表现出前一种行为,而另一些会表现出后者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.