【问题标题】:ContainsKey on TreeMap throws NPETreeMap 上的 ContainsKey 引发 NPE
【发布时间】:2017-03-23 23:46:39
【问题描述】:

所以我有一个Comparator,我为我的TreeMap 定义了按值对其进行排序, 但是当我在一个不包含它的键上使用containsKey(anyKey) 时,它不会返回错误,而是会抛出一个NullPointerException。现在我不明白的是为什么它会在我的比较器中使用containsKey() 方法以及我如何找到解决方案......我已经坚持了几个小时,任何帮助都会得到帮助。

代码如下:

public class test {

    public static void main(String[] args) {

        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(1,2);
        map.put(2, 3);
        Comparator<Integer> comp = new ValueComparator<Integer, Integer>(map);
        TreeMap<Integer, Integer> tm = new TreeMap<Integer, Integer>(comp);
        tm.putAll(map);
        System.out.println(tm.containsKey(1)); // returns true
        System.out.println(tm.containsKey(3)); //Throws NPE
    }


}

class ValueComparator<K, V extends Comparable<V>> implements Comparator<K>{

    HashMap<K, V> map = new HashMap<K, V>();

    public ValueComparator(HashMap<K, V> map){
        this.map.putAll(map);
    }

    @Override
    public int compare(K s1, K s2) {

        return map.get(s1).compareTo(map.get(s2));//descending order    
    }
}

【问题讨论】:

  • 发布您的堆栈跟踪
  • 其实很明显。您的 compare() 方法不会检查密钥是否在地图中。您需要决定如何处理未映射的键。
  • containsKey 需要将您检查的值与树中的值进行比较,但 3 不在您提供给比较器的地图中
  • 好吧,我知道我不检查它是否在我的地图中(所以 get 返回 null)但是如果它不在我的地图中怎么办? (我是这些结构的新手,也许不确定这一切是如何工作的,如果这看起来有点愚蠢,很抱歉)感谢您的回答
  • @shmosel 非常感谢,现在更有意义了 :)

标签: java comparator treemap


【解决方案1】:
@Override
public int compare(K s1, K s2) {
    // Here is the problem you need to check if map.get(s1) returns null.
    return map.get(s1).compareTo(map.get(s2));//descending order    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 2015-05-22
    • 2019-04-06
    相关资源
    最近更新 更多