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));
}
}
这段代码有什么错误?
答案 0 :(得分:4)
您的数组应该是引用类型:
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