7

Got to implement the method below for an assignment which it's subject is "WildCards", but don't know where to use wildcards in order to resolve the warning.

static <T extends Comparable> T findMax(T ... items)
{
    T max = items[0];
    for (T item : items)
        if (item.compareTo(max) > 0)
            max = item;
    return max;
}

Any ideas ?

3
  • 1
    See this answer on why you have to change <T extends Comparable> to <T extends Comparable<T>>
    – pafau k.
    May 31, 2020 at 22:02
  • 1
    A comment on the code: since arrays are covariant, while generics are invariant, using a generic varargs parameter may set you up for trouble.
    – Turing85
    May 31, 2020 at 22:03
  • Should be safe, as the array is only ever queried, not modified though?
    – pafau k.
    May 31, 2020 at 23:20

1 Answer 1

13

Comparable is a generic interface, so to use it safely you must always specify the generic type to use. In your case, something like:

<T extends Comparable<T>>

is likely what you're looking for. Otherwise, the compiler is unable to help you verify that the types are actually compatible in all scenarii.

6
  • Thank you that solved the warning. But not every time T is going to be compared with its own type. How can I handle that (It's type is neither its super nor its child) ? . When I put ? instead of T in Comparable<T> I get the error Required type: 'capture of ?' , Provided : 'T' May 31, 2020 at 22:30
  • I don't think there will be any practical case where comparing two objects of completely unrelated types will be necessary or useful. It just seems like poor design. You'd use <Object>, but please never do that :p
    – Dici
    May 31, 2020 at 22:42
  • How would you even onctruct such a call? Even if your type T is a Comparable<Object>, how could you pass anything other than T as a method parameter?
    – pafau k.
    May 31, 2020 at 23:22
  • Like this: gist.github.com/Dicee/e54be66700bf4534d49d2c24b564e62a
    – Dici
    Jun 1, 2020 at 9:33
  • Well unfortunately only for the sake of learning T was comparable only with type which was neither its child nor its parent :) Jun 1, 2020 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.