为什么 TreeMap 中不允许空键?

Why null key is not allowed in TreeMap?

我试图理解 Java 集合框架背后的概念,并提出了这个问题 - 为什么 TreeMap 中不允许空键?

如果我们尝试在 TreeMap 中添加空键,它会给出 NullPointerException。

尝试 google TreeMap 的内部工作,发现像 TreeMap 这样的东西使用 RedBlack 树算法,这对我来说现在很难理解,我正在研究它。

TreeMap is a Red-Black tree based NavigableMap implementation.In other words , it sorts the TreeMap object keys using Red-Black tree algorithm.

请解惑,另外两个Map接口的实现允许null作为键,那么为什么TreeMap不允许添加null作为键?

谢谢你的解释。

TreeMap 允许空键。默认的自然排序比较器是抛出异常的比较器。

来自TreeMap.putdocumentation

NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys

允许空值的最简单方法是使用 Comparator.nullsFirst(Comparator.naturalOrder())Comparator.nullsLast(Comparator.naturalOrder())

等比较器创建 TreeMap

我的印象是 Treemap 不允许任何空键,但是在使用 java 6 时我发现我可以在树图中使用 null 键添加第一个元素, 但对于 java 8 情况并非如此。

 Map<String, Date> productStartDatesBySourceProductID = new TreeMap<String, Date>();