java中的方法泛型

java中的方法泛型,java,generics,Java,Generics,我必须创建一个getTotal函数来查找2d数组中所有数字的总和。 它应该适用于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

我必须创建一个getTotal函数来查找2d数组中所有数字的总和。 它应该适用于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;
}

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

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

基本类型和泛型不能很好地结合在一起。数组和泛型也不能很好地结合在一起。因此,基元类型数组和泛型数组几乎不兼容。您必须为每种类型的数组提供一种方法,就像
java.util.Arrays
对各种方法所做的那样。我恐怕JBNizet是正确的。如果需要该功能,只需重载所需类型的方法(Integer、Long等)。


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