简体   繁体   English

Comparable Generic 如何使用ist

[英]Comparable Generic how to use ist

I am very new in Java.我对Java很陌生。 I dont get the idea of this <T extends Comparable<T>> .我不明白这个<T extends Comparable<T>>的想法。 I mean why a T before extends?我的意思是为什么T之前延伸? Is that not enough to write extends Comparable<T> ?编写extends Comparable<T>还不够吗? Why extends and not implements in javadoc its an interface, right?为什么在 javadoc 中extends而不是implements它的接口,对吗? As I understand Comparable compares two objects?据我了解Comparable比较两个对象?

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

You're missing two things:你错过了两件事:

First, extends Comparable<T> is not for your TopNPrinter class (ie, the class TopNPrinter is not intended to implement the Comparable interface).首先, extends Comparable<T>不是您TopNPrinter类(即,类TopNPrinter并不旨在实现Comparable接口)。
When you see the syntax class TopNPrinter<T extends Comparable<T>> , then you have a generic class that declares a type parameter called T .当您看到语法class TopNPrinter<T extends Comparable<T>> ,您就有了一个泛型类,它声明了一个名为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. extends Comparable<T>T限制为实现Comparable接口的类型( T是泛型Comparable<T>接口的类型参数。

Second:第二:

Is that not enough to write extends Comparable<T>extends Comparable<T>还不够吗?

If you wrote如果你写

class TopNPrinter extends Comparable<T>

Then, unless T were an existing type, T would be undefined/unknown.然后,除非T是现有类型, T将是未定义的/未知的。 So, as mentioned above, T is being declared as the generic type parameter.因此,如上所述, T被声明为泛型类型参数。 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.我个人认为泛型常见问题对此非常有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM