Possible duplicate: Does this custom compare method contain a logical error
I try to sort location list with a default location. Which position close to default location is greater than other. Here is my try:
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;
}
The problem is it gives me a java.lang.IllegalArgumentException
like this:
java.lang.IllegalArgumentException: Comparison method violates its general contract!
I also search many answer on stackoverflow, but all of them not work for me. I understand method is not transitive but I don't know how to fix it. Any help would be appreciated.
Update: Here is my location entity:
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
}
Update 2: Finally it works, because it is my mistake. When the left location lat or long is null, it should be return 1 instead of -1. Here is the right code:
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;
}
Many thanks for rolfl
and other people.