2

I read that using a wildcard with super like this:

public class MyClass <T extends Comparable<? super T>> {
   ...
}

instead of:

public class MyClass <T extends Comparable<T>> {
   ...
}

could make the class 'more generic', but I do not understand why.

Can someone provide some concrete examples?

Kami
  • 1,079
  • 2
  • 13
  • 28
  • 2
    possible duplicate of [Java Generics: What is PECS?](http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs) – u3l Jul 07 '14 at 11:16
  • possible duplicate of [What is super T> syntax?](http://stackoverflow.com/questions/2827585/what-is-super-t-syntax) – Harry Blargle Jul 08 '14 at 11:32

1 Answers1

6

This way you can supply a class for T, which does not for itself implements Comparable, but inherits from a class implementing Comparable.

E.g.

class Baseclass implements Comparable<Baseclass> {
...
}

class Inherited extends Baseclass {
...
}

With a specification like

public class MyClass <T extends Comparable<? super T>> {
...
}

you can use MyClass<Inherited>, and MyClass<Baseclass>, but with

public class MyClass <T extends Comparable<T>> {
...
}

you can only use MyClass<Baseclass>

Uwe Allner
  • 3,399
  • 9
  • 35
  • 49
  • I actually tried that. I created a class Fruit which implements Comparable and 2 subclasses: Apple and Orange. Then, I tried to use a method written in this form > (note that I used no super keyword) and it compared apples with oranges nevertheless. Do you have any idea why? It should not work according to your answer. – Kami Jul 08 '14 at 10:23
  • Here is my other question: https://stackoverflow.com/questions/24629547/java-wildcard-with-super-unexpected-behaviour?noredirect=1#comment38171540_24629547 – Kami Jul 08 '14 at 11:09
  • @Kami You will see that when your MyClass has getters and setters accepting or delivering Objects of type T. This will not work without super. – Uwe Allner Jul 09 '14 at 06:59