Skip to content Skip to sidebar Skip to footer

Does This Custom Compare Method Contain A Logical Error

In an android application, I have a list of locations. I need to sort them based on their distance with the user location. for that I implemented a custom comparator: Collections.s

Solution 1:

As Peter Lawrey said, you should use Double.compare(x, y) or Float.compare(x, y) instead of casting to int. Here the explanation:

Comparator MUST be transitive, i.e. whenever A == B and B == C, then also A == C. Lets imagine we have three points A, B and C with the distances to the user location 0.2, 0.4 and 1.3.

  1. (int) (0.2 - 0.4) = (int) (-0.2) = 0 => A == B
  2. (int) (0.4 - 1.3) = (int) (-0.9) = 0 => B == C
  3. (int) (0.2 - 1.3) = (int) (-1.1) = -1 => A < C

As you can see the comparator is not transitive.

Solution 2:

If userLocation == null then house1.equals(house2) should give true.

Post a Comment for "Does This Custom Compare Method Contain A Logical Error"