gpt4 book ai didi

java - java中的泛型方法

转载 作者:太空宇宙 更新时间:2023-11-04 15:24:25 25 4
gpt4 key购买 nike

我必须创建一个 getTotal 函数来查找二维数组中所有数字的总数。它应该适用于 float、int、long 和 double。所以我尝试用 Java 创建一个通用方法。我了解 C++ 中的模板。所以我尝试了类似的方法,但 java 编译器显示错误。

public static < E > E getTotal( E arr[][],int row, int col )
{
E total=0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
total=total + arr[i][j];
}
}
return total;
}

我收到这些错误:



2darray.java:4: error: incompatible types
E total=0;
^

required: E
found: int
where E is a type-variable:
E extends Object declared in method getTotal(E[][],int,int)
2darray.java:7: error: bad operand types for binary operator '+'
total=total + arr[i][j];
^
first type: E
second type: E
where E is a type-variable:
E extends Object declared in method getTotal(E[][],int,int)
2darray.java:42: error: method getTotal in class darraysoperation cannot be applied to given types;
System.out.println("Total is "+foo.getTotal(multi,5,10));
^
required: E[][],int,int
found: int[][],int,int
reason: inferred type does not conform to declared bound(s)
inferred: int
bound(s): Object
where E is a type-variable:
E extends Object declared in method getTotal(E[][],int,int)
3 errors



我没有收到这些错误,因为我是 Java 泛型的初学者。

最佳答案

E 是泛型类型。这意味着您可以使用任何类型的数组调用 getTotal 方法。例如,您可以使用字符串数组调用 getTotal,但 0 不是字符串。

关于java - java中的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20018164/

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