This will be slow.
It seems add
operation will eventually require O(N)
, where N
is number of existing cities in the collection. This will be slower and slower as more cities are added.
I can't think of a way to lazy-evaluate the distance. It seems to me all-pair distances must be calculated up front. Maybe someone can offer better suggestions.
Remark. SortedMap
Seems wrong. It doesn't allow duplicate keys (two doubles
having same value). However, the chances of two pairs of cities with same distance seems remote to me ...
public class CityCollection
{
private List<City> cities;
// Cache distances when cities added, because expensive to calculate
private Map<Pair<City, City>, double> distances;
// sorted by pairwise distances
private SortedMap<double, Pair<City, City>> sortedByDistances;
public void add(City city)
{
if (cities.contains(city)) return;
for (City oldCity : cities)
{
Pair<City, City> pair = new Pair<City, City>(oldCity, city);
double distnace = getDistance(oldCity, city);
distances.put(pair, distance);
sortedByDistances.put(distance, pair);
}
cities.add(city);
}
// this is possibly very very slow, or very very fast...
public static double getDistance(City origin, City destination)
{
Query q = new Query(
origin.getCentroid().toString(),
destination.getCentroid().toString(),
"GreatCircle");
// .. wait for query to finish
return q.distance();
}
// implement your other methods here
}
member
methods on theCity
class and that they should only need to take the second parameter and use the instance as the first one. As it is now, these look likestatic
methods and that would be a brittle design in Java. 4 and 5 look like good candidates forstatic
methods as they are.static
does not seem to work.