java - bad operand types for binary operator '+' -
this question has answer here:
- java: generic methods , numbers 4 answers
i working on creating generic class manipulate matrices. here problem: when implement addition operation, "bad operand types binary operator '+'"
it says that:
first type: object second type: t t type-variable: t extends object declared in class matrix
is there way make addition?
here code:
public class matrix<t> { private t tab[][]; public matrix( t tab[][]) { this.tab = (t[][])new object[tab.length][tab[0].length]; for(int = 0; < tab.length; i++){ system.arraycopy(tab[i], 0, this.tab[i], 0, tab.length); } } public matrix(int row, int column) { this.tab = (t[][])new object[row][column]; } //other constructors... public matrix addition(matrix othermatrix) { matrix tmp = new matrix(othermatrix.getrowlen(), othermatrix.getcollen()); for(int = 0; < tab.length; i++){ for(int j = 0; j < tab[0].length; j++){ //the line error below tmp.setelement(i, j, othermatrix.getelement(i, j) + tab[i][j]); } } return tmp; } public int getrowlen(){ return tab.length; } public int getcollen(){ return tab[0].length; } public void setelement(int i, int j, t value){ tab[i][j] = value; } public void setelement( t tab[][]) { this.tab = (t[][])new object[tab.length][tab[0].length]; for(int = 0; < tab.length; i++){ system.arraycopy(tab[i], 0, this.tab[i], 0, tab.length); } } public t getelement(int i, int j){ return tab[i][j]; } }
thanks in advance !
java doesn't support using +
operator primitive numeric types , strings
. here, can't use +
operator between arbitrary objects.
you got object
left hand side because othermatrix
raw (untyped) matrix
. got t
right hand side because tab
defined generically t
.
you cannot overload operators in java, cannot have +
defined t
.
you may able want removing generics , using
private int tab[][];
or
private double tab[][];
depending on needs.
Comments
Post a Comment