gpt4 book ai didi

java - 如何将数组传递给由 Comparable 接口(interface)限制的类型参数

转载 作者:行者123 更新时间:2023-12-02 09:24:58 24 4
gpt4 key购买 nike

我有一个界面:

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接口(interface)但它没有解释如何使用它来实际计算数组中大于指定元素的元素数量,我的意思是它没有解释如何调用该方法并向其传递一个数组和指定元素。我也不明白方法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;
}

方法说它可以接受任何实现 Comparable 的东西界面。 Integer类确实实现了 Comparable。为了更好地理解,您必须阅读更多关于 Generics 的内容。 Angelika Langer为我列出了最好的解释。

关于java - 如何将数组传递给由 Comparable 接口(interface)限制的类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com