public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
...
}
final int compare(Object k1, Object k2) {
return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
: comparator.compare((K)k1, (K)k2);
}
在遇到应用程序中的一些错误之后,我不得不调试TreeMaps put方法。我的问题是比较放置在地图中的对象。奇怪的是,当我将FIRST元素添加到Map时,它的键与自身进行了比较。我不明白为什么会这样工作。有什么见解(除了注释的“类型(可能为空)检查”之外)?他们为什么不只检查key是否为null?在那里进行什么样的“类型”检查?
如评论中所述,https://bugs.openjdk.java.net/browse/JDK-5045147是引入此问题的问题。从该问题的讨论中,最初的解决方法是:
BT2:建议的修复
道格·李写道:
“谢谢!我对deja vu有很强的意识,我已经在(!)之前添加了此功能,但是Treemap.put应该添加以下陷阱。”
public V put(K key, V value) { Entry<K,V> t = root; if (t == null) { + if (key == null) { + if (comparator == null) + throw new NullPointerException(); + comparator.compare(key, key); + } incrementSize(); root = new Entry<K,V>(key, value, null); return null; }
如果的比较器TreeMap
为空,或者比较器不接受空键(符合API规范),则似乎打算抛出NPE 。似乎解决方法缩短为一行:
compare(key, key);
定义为:
@SuppressWarnings("unchecked")
final int compare(Object k1, Object k2) {
return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
: comparator.compare((K)k1, (K)k2);
}
因此,此测试将同时执行null检查和类型检查,即进行类型转换Comparable
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句