I need to build a class Course
which has a generic field (I can't add another field containing Comparator
).
I need to make a Comparator
to the class Course
to make it possible to compare the generic field using it's own CompareTo
method (if String-compareTo
by string, if by Integer etc..):
the mothod getGeneric()
returns the generic field.
new Comparator<Course<?>>( {
public int compare(Course<?> o1, Course<? extends Comparable<?>> o2) {
return (o1.getGeneric()).compareTo(o2.getGeneric());
}
});
What you should probably do is to have a method that declares a comparable
T
, and returns aComparator<Course<T>>
.There are ways to do this without creating a new instance each time, but they require circumventing the type system, so they're more advanced. The above should be fine for most use cases.
You could also have that
comparator
function take aComparator<T>
itself:This gives you extra flexibility, as well as the ability to create comparators for types that don't have natural comparisons (ie, that don't implement
Comparable
). For instance, you could create aComparator<Course<Course<Integer>>>
!