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 ?

Parsa Noori
  • 198
  • 1
  • 1
  • 10
  • 1
    See [this answer](https://stackoverflow.com/questions/8537500/java-the-meaning-of-t-extends-comparablet) on why you have to change `` to `>` – pafau k. May 31 '20 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 '20 at 22:03
  • Should be safe, as the array is only ever queried, not modified though? – pafau k. May 31 '20 at 23:20

1 Answers1

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.

Dici
  • 25,226
  • 7
  • 41
  • 82
  • 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` I get the error `Required type: 'capture of ?' , Provided : 'T' ` – Parsa Noori May 31 '20 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 ``, but please never do that :p – Dici May 31 '20 at 22:42
  • How would you even onctruct such a call? Even if your type `T` is a `Comparable`, how could you pass anything other than `T` as a method parameter? – pafau k. May 31 '20 at 23:22
  • Like this: https://gist.github.com/Dicee/e54be66700bf4534d49d2c24b564e62a – Dici Jun 01 '20 at 09:33
  • Well unfortunately only for the sake of learning T was comparable only with type which was neither its child nor its parent :) – Parsa Noori Jun 01 '20 at 21:03
  • or even better, `>` – newacct Sep 07 '20 at 21:27