[英]method generics in java
我必須創建一個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。 例如,您可以使用String數組調用getTotal,而0不是String。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.