自己调试代码的时候发现TreeMap.get, TreeMap.remove都拿不到正确的值(返回null)。
后来发现,原因是TreeMap的实现,为了加速,使用了基于Comparator的查找:
final Entry<K,V> getEntry(Object key) {
// Offload comparator-based version for sake of performance
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
Entry<K,V> p = root;
while (p != null) {
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
如果comparator有问题的话自然get, remove也会有问题了。