gpt4 book ai didi

java - 在java泛型方法中发送数组作为参数

转载 作者:行者123 更新时间:2023-12-01 17:50:50 26 4
gpt4 key购买 nike

class MaximumTest {
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> int CountDuplicates(T[] anArray, T elem) {
int count = 0;
for (T e: anArray)
if (e.compareTo(elem) == 0)
++count;
return count;
}
public static void main(String args[]) {
double[] D_arr = {
1.2, 3.4, 0.0, 4.5, 0.0
};
int[] I_arr = {
0, 0, 0, 0, 1, 3, 5
};
System.out.println("No of zeros in Double Array = " + CountDuplicates(D_arr, 0.0));
System.out.println("No of zeros in Double Array = " + CountDuplicates(I_arr, 0));
}
}

这段代码有什么错误?

最佳答案

您的数组应该是引用类型:

Double[] D_arr = {1.2, 3.4, 0.0, 4.5, 0.0};
Integer[] I_arr = {0,0,0,0,1,3,5};

原始类型不能用作泛型类型。

进行此更改后,您的代码将通过编译并生成输出:

No of zeros in Double Array = 2
No of zeros in Double Array = 4

关于java - 在java泛型方法中发送数组作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50351539/

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