问题
重写了TreeMap的Comparator,TreeMap在get的时候通过Comparator比较,如果小于0,往左找,大于0往右找,不等于0的话,最后是会返回null。源码如下:
final Entry<K,V> getEntry(Object key) {
// Offload comparator-based version for sake of performance
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
Entry<K,V> p = root;
while (p != null) {
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
解决
方案一:Comparator在相等的时候返回0
Map<String, Object> newTreeMap = new TreeMap<>((o1, o2) -> {
// 定义匹配的条件
if(o1.key == o2.key){
return 0;
}
// 处理其他的比较
...
});
方案二:转成HashMap或者LinkedHashMap
Map<String, Object> map = new HashMap<>(newTreeMap);