user3008845
user3008845

Reputation: 1

Java Generics and exetends Comparable

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());
    }
});

Upvotes: 0

Views: 121

Answers (1)

yshavit
yshavit

Reputation: 43391

What you should probably do is to have a method that declares a comparable T, and returns a Comparator<Course<T>>.

public static <T extends Comparable<T>> Comparator<Course<T>> comparator() {
    return new Comparator<Course<T>>() {
        @Override
        public int compare(Course<T> o1, Course<T> o2) {
            // I don't want to give away TOO much. :)
        }
    }
}

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 a Comparator<T> itself:

public static <T> Comparator<Course<T>> comparator(Comparator<T> innerComparator) {
    ...
}

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 a Comparator<Course<Course<Integer>>>!

Upvotes: 5

Related Questions