可能的重复:Does this custom compare method contain a logical error
我尝试使用默认位置对位置列表进行排序。靠近默认位置的位置大于其他位置。这是我的尝试:
public int compare(Location lhs, Location rhs) {
if(lhs == null && rhs == null){
Ln.d("l1, l2 are null");
return 0;
}
if(lhs == null && rhs != null){
Ln.d("l1 is null");
return -1;
}
if(lhs != null && rhs == null){
Ln.d("l2 is null");
return 1;
}
float[] result1 = new float[1];
float[] result2 = new float[1];
double startLat;
double startLng;
double endLat;
double endLng;
double defaultLat = getDefaultLocation().getLatitude();
double defaultLng = getDefaultLocation().getLongitude();
// because sometime location is null:
try{
startLat = Double.parseDouble(lhs.getLat());
startLng = Double.parseDouble(lhs.getLng());
}catch(Exception ex){
return 1;
}
try{
endLat = Double.parseDouble(rhs.getLat());
endLng = Double.parseDouble(rhs.getLng());
}catch(Exception ex){
return -1;
}
android.location.Location.distanceBetween(startLat, startLng, defaultLat, defaultLng, result1);
android.location.Location.distanceBetween(endLat, endLng, defaultLat, defaultLng, result2);
int result = Double.compare(result1[0], result2[0]);
Ln.d("result 1 = " + result1[0] + ", result 2 = " + result2[0] + " and result = " + result);
return result;
}
问题是它给了我一个 java.lang.IllegalArgumentException
像这样:
java.lang.IllegalArgumentException: Comparison method violates its general contract!
我还在 stackoverflow 上搜索了很多答案,但它们都不适合我。我知道方法不可传递,但我不知道如何修复它。任何帮助将不胜感激。
更新:这是我的位置实体:
public class Location{
private long id;
private String provider_name;
private String display_address;
private String lat;
private String lng;
private int zoom;
private String contact;
private String website;
private String email;
// getters & setter
}
更新2:终于成功了,因为这是我的错误。当左侧位置纬度或经度为空时,应返回 1 而不是 -1。这是正确的代码:
try{
startLat = Double.parseDouble(lhs.getLat());
startLng = Double.parseDouble(lhs.getLng());
}catch(Exception ex){
return 1;
}
try{
endLat = Double.parseDouble(rhs.getLat());
endLng = Double.parseDouble(rhs.getLng());
}catch(Exception ex){
return -1;
}
非常感谢rolfl
和其他人。
最佳答案
您也可以采用这种方法:
Collections.sort(yourLocations, new Comparator<Location>() {
@Override
public int compare(Location o, Location o2) {
final Float distance1 = currentLocation.distanceTo(o);
final Float distance2 = currentLocation.distanceTo(o2);
return distance1.compareTo(distance2);
}
});
关于java - Android 排序位置列表 - java.lang.IllegalArgumentException : Comparison method violates its general contract,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19770271/