二元运算符“+”的不良操作数类型
问题描述:
我正在创建一个操作矩阵的泛型类。但这里有一个问题:当我执行加法运算,我得到一个“坏的操作类型的二进制运算符‘+’”二元运算符“+”的不良操作数类型
它说:
第一类:对象 第二类: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不支持将+
运算符用于除原始数字类型和Strings
之外的任何其他运算符。在这里,您不能在任何任意对象之间使用+
运算符。
由于otherMatrix
是原始(无类型)Matrix
,因此您得到了左手边的Object
。右边有T
,因为tab
一般定义为T
。
您不能在Java中重载操作符,因此您不能为T
定义+
。
您可以得到你想要的东西通过删除泛型和使用
private int tab[][];
或
private double tab[][];
根据您的需要。
答
尽管数学运算符不适用于泛型类型(即使受到Number
限制,请参阅suggested duplicate),但您可以在创建矩阵时轻松地传递数学运算的策略。
public class Matrix<T> {
private final MathOperations<T> operations;
public Matrix(T[][] data, MathOperations<T> operations) {
//...
this.operations = operations;
}
//...
tmp.setElement(i, j, operations.add(otherMatrix.getElement(i, j), tab[i][j]));
}
public interface MathOperations<T> {
public T add(T operand1, T operand2);
//... any other methods you need defined
}
public class IntegerMathOperations implements MathOperations<Integer> {
public Integer add(Integer i1, Integer i2) {
//(assuming non-null operands)
return i1 + i2;
}
}
不能在java中做操作符重载。 – 2013-05-09 16:31:00
[Java:Generic methods and numbers]的可能重复(http://*.com/questions/3850970/java-generic-methods-and-numbers)。另请参阅:[Java泛型和Number类](http://*.com/questions/3923081/java-generics-and-the-number-class) – 2013-05-09 16:32:06