TreeMap的Comparator, 要慎用

来源:互联网 发布:eve ios软件 编辑:程序博客网 时间:2024/04/29 23:06

自己调试代码的时候发现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也会有问题了。