Search code examples
javagenericsinterfaceabstractcomparable

Comparable Generic how to use ist


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);
    }

Solution

  • 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.