本人初学java,最近学习java泛型,遇到了一些问题,如下:public class Matrix<T extends Number>{
int cols;
int rows;
Class<T> type;
T[] data = null; public Matrix(int cols, int rows){
//.....
data = (T[])Array.newInstance(type, cols * rows);
}
public Matrix<T> add(Matrix<T> x){
//.....
T y = data[0] + x.data[0];//这里说T没有定义+运算符,该怎么解决呢?
}
}Java泛型
int cols;
int rows;
Class<T> type;
T[] data = null; public Matrix(int cols, int rows){
//.....
data = (T[])Array.newInstance(type, cols * rows);
}
public Matrix<T> add(Matrix<T> x){
//.....
T y = data[0] + x.data[0];//这里说T没有定义+运算符,该怎么解决呢?
}
}Java泛型
比如说:
Integer x = 1;
Integer y = 2;
Integer z = x + y;//这样做是可以的
Number类有个doubleValue() 方法,多查API!
但是我的意思是:使用泛型的意义在于,它适合各种数据类型,如果使用Number.xxxValue()这种方式的话,就没有使用泛型的必要了我直接只定义Matrix类的data为double类型就可以了
把int都改为Integer试试。。