简体   繁体   中英

method generics in java

I have to create a getTotal function to find total of all number in a 2d array. It should be applicable to float,int,long and double. So I tried to create a generic method in Java. I have knowledge of templates in C++. So I tried a similar approach but java compiler is showing errors.

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;
}

I am getting these errors :



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



I am not getting these errors as I am beginner to generics in Java.

E is generic type. it means that you can call method getTotal with array of any type. for example you can call getTotal with array of String and 0 is not String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM