我正在创建一个操作矩阵的泛型类。但这里有一个问题:当我执行加法运算,我得到一个“坏的操作类型的二进制运算符‘+’”二元运算符“+”的不良操作数类型
它说:
第一类:对象 第二类:T 哪里T是一个类型变量: T extends Object在类中声明的对象
有没有办法让它做添加?
这里是我的代码:
public class Matrix<T> {
private T tab[][];
public Matrix(T tab[][])
{
this.tab = (T[][])new Object[tab.length][tab[0].length];
for(int i = 0; i < 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 i = 0; i < tab.length; i++){
for(int j = 0; j < tab[0].length; j++){
//the line with the error is 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 i = 0; i < 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];
}
}
在此先感谢!
不能在java中做操作符重载。 – 2013-05-09 16:31:00
[Java:Generic methods and numbers]的可能重复(http://stackoverflow.com/questions/3850970/java-generic-methods-and-numbers)。另请参阅:[Java泛型和Number类](http://stackoverflow.com/questions/3923081/java-generics-and-the-number-class) – 2013-05-09 16:32:06