最近再做一个需求,kv的数据格式,要求对 k进行倒序遍历,于是想到了TreeMap,因为 TreeMap 默认升序排列,因此需要自定义一个Comparator,代码如下:
public static Comparator<Double> comparator = new Comparator<Double>() {
@Override
public int compare(Double o1, Double o2) {
// TODO Auto-generated method stub
if (o1 < o2) {
return 1;
} else if (o1 == o2) {//错误的地方
return 0;
} else {
return -1;
}
}
};
TreeMap 代码段:
Map<Double, Double> negativeMap = new TreeMap<Double, Double>(Constant.comparator);
positiveMap.put(4, 4);
positiveMap.put(4, 4);
positiveMap.put(4, 4);
double i=1;
for(Double key: negativeMap.keySet()){
Double tmpValue = negativeMap.get(key);
result += tmpValue/i;//出现空指针
i++;
}
这段代码正常看 无论都不会出现空指针,我正常put三条数据,即使key 相等,也会覆盖掉,不会出现NP,但事实就是出现了,而且打