aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/sorting/DistanceComparator.java
blob: f4005832de857e29d9b2d535abbdb9576e1834dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package cgeo.geocaching.sorting;

import cgeo.geocaching.Geocache;
import cgeo.geocaching.location.Geopoint;

import java.util.ArrayList;
import java.util.List;

/**
 * sorts caches by distance to given position
 *
 */
public class DistanceComparator extends AbstractCacheComparator {

    final private Geopoint coords;
    final private List<Geocache> list;
    private boolean cachedDistances;

    final static public DistanceComparator singleton = new DistanceComparator();

    public DistanceComparator() {
        // This constructor should not be used as a comparator as distances will not be updated.
        // It is needed in order to really know we are sorting by Distances in the sort menu.
        // If you need it for sorting, please use the second constructor.
        coords = null;
        list = new ArrayList<>();
    }

    public DistanceComparator(final Geopoint coords, final List<Geocache> list) {
        this.coords = coords;
        // create new list so we can iterate over the list in parallel with the cache list adapter
        this.list = new ArrayList<>(list);
    }

    /**
     * calculate all distances only once to avoid costly re-calculation of the same distance during sorting
     */
    private void calculateAllDistances() {
        if (cachedDistances) {
            return;
        }
        for (final Geocache cache : list) {
            if (cache.getCoords() != null) {
                cache.setDistance(coords.distanceTo(cache.getCoords()));
            }
        }
        cachedDistances = true;
    }

    @Override
    protected int compareCaches(final Geocache cache1, final Geocache cache2) {
        calculateAllDistances();
        final Float distance1 = cache1.getDistance();
        final Float distance2 = cache2.getDistance();
        if (distance1 == null) {
            return distance2 == null ? 0 : 1;
        }
        return distance2 == null ? -1 : Float.compare(distance1, distance2);
    }

}