TreeMap上的ContainsKey抛出NPE

时间:2017-03-23 23:46:40

标签: java comparator treemap

所以我有一个Comparator我为我的TreeMap定义了按值排序, 但是当我在一个不包含它的键上使用containsKey(anyKey)时,它不会返回false,但会抛出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    
    }
}

1 个答案:

答案 0 :(得分:-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    
}
相关问题