3

I am very new in Java. I dont get the idea of this <T extends Comparable<T>>. I mean why a T before extends? Is that not enough to write extends Comparable<T>? Why extends and not implements in javadoc its an interface, right? As I understand Comparable compares two objects?

public class TopNPrinter<T extends Comparable<T>> {
    private int N;
    private String header;

    public TopNPrinter(int N, String header) {
        this.N = N;
        this.header = header;
    }

    private List<T> getTopN(List<T> list) {
        List<T> copy = new ArrayList<>(list);
        Collections.sort(copy);
        return copy.subList(0, N);
    }
ernest_k
  • 44,416
  • 5
  • 53
  • 99
Sayuri
  • 63
  • 6
  • 2
    Aside: it's a little better to use `>` anyway. – Andy Turner Dec 10 '19 at 11:49
  • why is it better to use super T>>? – Sayuri Dec 10 '19 at 13:57
  • @Sayuri: "why is it better to use super T>>" Consider if `Animal extends Comparable`, and `Dog extends Animal`, then with `>`, `TopNPrinter` would compile while `TopNPrinter` wouldn't, even though any `Dog` object can compare to any other `Dog` object (as well as other `Animal`s). `>` fixes that. Another way to look at it is `Comparable` is a "consumer" (`T` is only used as method parameter types), and therefore according to the PECS rule should always be used with a `? super` wildcard. – newacct Jan 18 '20 at 20:29

1 Answers1

1

You're missing two things:

First, extends Comparable<T> is not for your TopNPrinter class (i.e., the class TopNPrinter is not intended to implement the Comparable interface).
When you see the syntax class TopNPrinter<T extends Comparable<T>>, then you have a generic class that declares a type parameter called T. extends Comparable<T> limits T to types that implement the Comparable interface (with T being the type argument to the generic Comparable<T> interface.

Second:

Is that not enough to write extends Comparable<T>

If you wrote

class TopNPrinter extends Comparable<T>

Then, unless T were an existing type, T would be undefined/unknown. So, as mentioned above, T is being declared as the generic type parameter. Again, the fundamental problem here is that one needs to understand generics and how generic types are declared. I personally find the generics faq very helpful for this.

ernest_k
  • 44,416
  • 5
  • 53
  • 99