i have a class Car representing name and IDs of cars:
public class Car {
String name;
int ID;
}
and another class representing races in which i
I would not do this with a SortedSet, even though a custom Comparator could be used. The reason is because the races could be modified and thus invalidate any structure inside the TreeSet making the behavior "unpredictable".
Instead, I would make getSortedCars
first get a sequence (e.g. a List) from the Set, and then sort and return such a sequence.
The actual sorting is "trivial" with Collections.sort and a custom Comparator as this is really a "sort by" operation, for instance:
class CompareCarsByWins implements Comparator<Car> {
Map<Car,Integer> wins;
public CompareCarsByWins(Map<Car,Integer> wins) {
this.wins = wins;
}
public int compareTo (Car a, Car b) {
// Actual code should handle "not found" cars as appropriate
int winsA = wins.get(a);
int winsB = wins.get(b);
if (winsA == winsB) {
// Tie, uhm, let's .. choose by name
return a.getName().compareTo(b.getName());
} else {
// Sort most wins first
return winsB - winsA;
}
}
// ..
}
// Usage:
List<Car> results = new ArrayList<Car>(cars);
Collections.sort(results, new CompareCarsByWins(races));