我试图理解 Java Collection 框架背后的概念并提出了这个问题 - 为什么 TreeMap 中不允许空键?
如果我们尝试在 TreeMap 中添加空键,它会给出 NullPointerException。
尝试用谷歌搜索 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 接口(interface)的其他两个实现允许 null 作为键,但为什么 TreeMap 不允许添加 null 作为键?
我想提前感谢您的解释。
最佳答案
TreeMap
允许空键。默认的自然顺序比较器是抛出异常的比较器。
来自documentation TreeMap.put
的:
NullPointerException
- if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
允许空值的最简单方法是创建带有比较器的 TreeMap
,例如 Comparator.nullsFirst(Comparator.naturalOrder())
或 Comparator.nullsLast (Comparator.naturalOrder())
关于java - 为什么 TreeMap 中不允许空键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48687829/