我很想对一个项目数组进行排序,如果一个项目的 id 等于所选项目的 id(也属于该数组),则该项目应该被带到数组的开头。其余元素的排序顺序是它们与给定位置的距离。
我java.lang.IllegalArgumentException: Comparison method violates its general contract!
在自定义比较器中遇到了可怕的异常,实现如下:
Location location = ...; // may be null
Item selectedItem = ...; // may be null or an element of the array to be sorted
private final Comparator<Item> comparator = new Comparator<Item>() {
@Override
public int compare(Item p1, Item p2) {
// if p1 is the currently selected item, bring p1 to the top
// if p2 is the currently selected item, bring p2 to the top
// else sort p1 and p2 by their distance from location
if (selectedItem != null) {
if (selectedItem.getId() == p1.getId()) { //id's are int and unique in the array
return -1;
} else if (selectedItem.getId() == p2.getId()) {
return 1;
}
}
if (location != null) { //location is an Android Location class instance
Float distance1 = location.distanceTo(p1.getLocation());
Float distance2 = location.distanceTo(p2.getLocation());
return distance1.compareTo(distance2);
} else {
return 0;
}
}
};
我没有复制问题的确切顺序,但是到目前为止,所有对错误的观察都发生在selectedItem
并且location
不为空(它们可能都为空)时。
有什么提示吗?
谢谢