我有一个带有自定义比较器的 TreeSet,但 remove() 操作不起作用。 这是代码:
new TreeSet<>(new Comparator<Tile>(){
public int compare(Tile o1, Tile o2){
if(o1 == o2){
return 0;
}
if(o1.getValue() > o2.getValue()){
return 1;
}
return -1;
}
});
我认为,对于这个比较器,一个副本被定义为 o1 == o2,并且 de order 是基于 getValue() 升序排列的。但是出了点问题.. 什么?
最佳答案
o1 == o2
这是比较对象引用,而不是值。您没有涵盖值相等的情况。假设对 getValue()
的调用并不昂贵,我通常会跳过对象引用相等性检查以使我的代码更简单一些。
public int compare(Tile o1, Tile o2){
if(o1.getValue() == o2.getValue()){
return 0;
}
if(o1.getValue() > o2.getValue()){
return 1;
}
return -1;
}
或者,更简单地说:
public int compare(Tile o1, Tile o2){
return o1.getValue() - o2.getValue();
}
关于java - 如何修复在 TreeSet 中使用的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27888478/