aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/sorting/DistanceComparator.java
blob: 781359a73ebf00d75d46608e3cf2a1c92e4e63ec (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.cgCache;
import cgeo.geocaching.geopoint.Geopoint;

import java.util.List;

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

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

    public DistanceComparator(final Geopoint coords, List<cgCache> list) {
        this.coords = coords;
        this.list = list;
    }

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

    @Override
    protected boolean canCompare(cgCache cache1, cgCache cache2) {
        return true;
    }

    @Override
    protected int compareCaches(final cgCache cache1, final cgCache cache2) {
        calculateAllDistances();
        if (cache1.getCoords() == null && cache2.getCoords() == null) {
            return 0;
        }
        if (cache1.getCoords() == null) {
            return 1;
        }
        if (cache2.getCoords() == null) {
            return -1;
        }
        return Float.compare(cache1.getDistance(), cache2.getDistance());
    }

}