treeMap-get返回null,因为比较器出问题

以上会get到null值,究其原因,可以从get方法源码中找到答案。TreeMap集合中实现Map集合的get代码如下:

    public V get(Object key) {
        Entry<K,V> p = getEntry(key);
        return (p==null ? null : p.value);
    }

  

再继续往下看 getEntry(key)方法:

 final Entry<K,V> getEntry(Object key) {
        // Offload comparator-based version for sake of performance
        if (comparator != null)
            return getEntryUsingComparator(key);
  //以下代码省略

 

这个时候就已经很明显了,他用到了我们传入的比较器!!!
接着往下看getEntryUsingComparator(key);

 final Entry<K,V> getEntryUsingComparator(Object key) {
        @SuppressWarnings("unchecked")
            K k = (K) key;
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {
            Entry<K,V> p = root;
            while (p != null) {
                int cmp = cpr.compare(k, p.key);
                if (cmp < 0)
                    p = p.left;
                else if (cmp > 0)
                    p = p.right;
                else
                    return p;
            }
        }
        return null;
    }

这个就很明白了,底层在往出取值的时候用到了我们传入的比较器中的compare()方法,TreeMap是二叉树结构存储数据。当我们拿着键去get值时,底层拿着我们传入的键去逐个比对此处调用比较器中的compare方法:小于零则往左边去找,大于零往右去找,只有当等于0时才返回该值,而我们强制compare()方法等于0的时候返回1,所以一直往右边去找,永远找不到,直到最后返回null

原文地址:https://www.cnblogs.com/qi-dev/p/13560856.html