java - java中的泛型方法

标签 java generics

我必须创建一个 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/

相关文章:

Java线程问题

java - 为什么这个方程不应该返回零?

用于类似动态类型转换的 Java 反射/通用类型

java - 获取抽象父类(super class)上泛型类型参数的实际类型

c++ - 两个不同类的通用函数

java - 泛型:基于泛型类的泛型类

java 。线程中的异常 "main"java.lang.IllegalArgumentException : adding a window to a container

java - 使用 JavaMail API 时出现 SSLException

java - 如果添加到包中则无法编译 jar

Java 泛型在 Eclipse 中编译,但在 javac 中不编译