java - Making a generic comparator class - Stack Overflow
The closest thing you can do to this is a Comparator
that can compare any objects that implement the Comparable
interface:
class NaturalComparator<T extends Comparable<T>> implements Comparator<T> { 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.
Read full article from java - Making a generic comparator class - Stack Overflow
No comments:
Post a Comment