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

问题描述 投票:0回答:1

我有一个界面:

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,Telem)传递一个整数数组,并且我也希望将该整数与数组中的元素进行比较?我最近在in this tutorial中了解了Compare接口,但是它没有解释如何使用它来实际计算数组中大于指定元素的元素数,因此,我的意思是它没有解释如何调用方法,并将其传递给数组和指定的元素。我还不明白properCountGreaterThan方法如何将指定的元素与数组的元素进行比较,因为方法compareTo(T o)没有实现,并且在properCountGreaterThan中调用时,它仅与0:

进行比较。
if (e.compareTo(elem) > 0) { count ++; }
java arrays generics comparable
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.