简体   繁体   中英

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

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>>> !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM