如何将数组传递给受 Comparable 接口限制的类型参数

How to pass an array to a type parameter bounded by the Comparable interface

我有一个界面:

public interface Comparable<T> {
    public int compareTo(T o);
}

限制方法中的类型参数

public static <T extends Comparable<T>> int properCountGreaterThan(T [] tArray, T elem) {
    int count = 0;
    for (T e : tArray) {
        if (e.compareTo(elem) > 0) { count ++; }
    }
    return count;
}

如何向方法 properCountGreaterThan(T [] tArray, T elem) 传递一个整数数组,以及我希望对数组元素进行比较的整数?我最近在 in this tutorial 中了解了 Compare 接口,但它没有解释如何使用它来实际计算数组中大于指定元素的元素数,我的意思是它没有解释如何调用该方法并将数组和指定元素传递给它。我也不明白 properCountGreaterThan 方法如何将指定元素与数组元素进行比较,因为方法 compareTo(T o) 没有实现,当它在 properCountGreaterThan 中被调用时,它只与 0:

进行比较
if (e.compareTo(elem) > 0) { count ++; }

您可以像这样将对象传递给该方法。

public static void main (String[] args)  {

    int num = countGreaterThan(new Integer[] {25,14,48,86}, 20);
}


public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
    int count = 0;
    for (T e : anArray)
        if (e.compareTo(elem) > 0)
            ++count;
    return count;
}

method 说它可以接受任何实现 Comparable interface. Integer class does implement Comparable. to understand better you have to read more about Generics Angelika Langer 的东西,在列表中对我进行了最好的解释。