Skip to Main Content

Java APIs


For appeals, questions and feedback, please email

Simple method but hard with generics: compareTo()

416044Feb 21 2005 — edited Nov 23 2005
I adjusted my getMaximum() method to generics to avoid the compiler warnings:
    static public Comparable<Comparable> getMaximum(Comparable<Comparable> comparable1, Comparable<Comparable> comparable2) {
        Comparable<Comparable> result = (comparable1 != null) ? comparable1 : comparable2; //init
        if (comparable1 != null && comparable2 != null) {
            int c = comparable1.compareTo(comparable2);
            result = (c > 0) ? comparable1 : comparable2; //comparable1 > comparable2?
        return result;
But now, my other classes that call this method e.g. with 2 dates or with 2 numbers don't compile anymore. I tried
    static public Comparable<? extends Comparable> getMaximum(Comparable<? extends Comparable> comparable1, Comparable<? extends Comparable> comparable2) {
        Comparable<? extends Comparable> result = comparable1; //default
        if (comparable1 != null && comparable2 != null) {
            int c = comparable1.compareTo(comparable2); //compile error
            if (c <= 0) {
                result = comparable2;
        } else if (comparable1 == null) {
            result = comparable2;
        return result;
but this code doesn't compile:

Bound mismatch: The method compareTo(? extends Comparable) of type
Comparable<? extends Comparable> is not applicable for the arguments
(Comparable<? extends Comparable>). The wildcard parameter ? extends
Comparable has no lower bound, and may actually be more restrictive than argument
Comparable<? extends Comparable>
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 21 2005
Added on Feb 21 2005