Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

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

Comments

Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Dec 21 2005
Added on Feb 21 2005
15 comments
1,917 views