The closest thing you can do to this is a Comparator
that can compare any objects that implement the Comparable
interface:
class NaturalComparator> implements Comparator {
public int compare(T a, T b) {
return a.compareTo(b);
}
}
That's really the closest you can do: only Comparable
objects have the "natural ordering" you're trying to model here. But generally, once you have Comparable
objects, you don't necessarily need a Comparator
: for example, Collections.sort
can take either a List
with a Comparator
, or a List
with Comparable
elements.