I'm seeing a lot of crashes on some Chinese Android phones for my app with the error: Comparison method violates its general contract!
I have read that it is something to do with the Collections.sort call.
The thing I'm not too sure about is if it is because of my custom Comparator or not.
Here is where the error occurs:
if (!airports.isEmpty()) {
Collections.sort(airports, new DistanceToAirportComparator(location));
return airports.get(0);
}
And the Comparator looks like this:
public class DistanceToAirportComparator implements Comparator<Airport> {
private final Location location;
public DistanceToAirportComparator(Location location) {
this.location = location;
}
@Override
public int compare(Airport airport1, Airport airport2) {
Location loc1 = getLocation(airport1);
Location loc2 = getLocation(airport2);
return Double.compare(location.distanceTo(loc1), location.distanceTo(loc2));
}
private Location getLocation(Airport airport){
Location location = new Location(LocationManager.GPS_PROVIDER);
location.setLatitude(airport.getLocation().getLatitude());
location.setLongitude(airport.getLocation().getLongitude());
return location;
}
So I'm not too sure if the Comparator is messing something up or not or if I need to do the collections.sort call in a different way
Appreciate any help
ComparatororComparable, you'll see the contract. Test your comparator code separately to see if it's possible to break the contract with it. - Kayaman