[英]ContainsKey on TreeMap throws NPE
So i have a Comparator
that i defined for my TreeMap
to sort it by values, but when i use containsKey(anyKey)
on a key that it does not contain it doesn't return false, but it throws a NullPointerException
.所以我有一个
Comparator
,我为我的TreeMap
定义了一个Comparator
来按值对其进行排序,但是当我在一个不包含它的键上使用containsKey(anyKey)
时,它不会返回 false,但它会抛出一个NullPointerException
。 Now what i don't understand is why it goes in my Comparator for the containsKey()
method and how i could find a solution... I've been stuck on this for a couple of hours and any help would be appriciated.现在我不明白的是为什么它在我的 Comparator 中使用
containsKey()
方法以及我如何找到解决方案......我已经坚持了几个小时,任何帮助都会得到帮助。
Here is the code :这是代码:
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
}
}
@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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.