通用稀疏矩阵加法 [英] Generic sparse matrix addition
问题描述
我有一个任务,我应该在通用稀疏矩阵上完成实现。我卡在添加部分。矩阵只会支持数字,所以我已经扩展数字希望我可以添加数字,这是错误的。数据结构不是一个数组,它基本上是2个链表。 (一个用于行,一个用于列)以下是有问题的代码:
public MatrixSparse <?扩展Number> (int i = 0; i< r.length; i ++){$ b())的加法(MatrixSparse< ;? extends Number> A,MatrixSparse<?extends Number> B,MatrixSparse< (i,j)和B(i,j)之和的$ b(int j = 0; j // set我错误
//+是未定义的类型捕获#2-?等等。
result.set(i,j,(A.get(i,j)+ B.get(i,j)));
}
}
返回结果;
}
以及类头+类变量:
class MatrixSparse< T extends Number> {
final Links r [];
最终链接c [];
final int rows,columns;
final T zero;
关于如何实现这个add方法的建议?
< ((整数)paramLeft).intValue()+((整数)paramRight).intValue()); code> if(paramLeft instanceof Integer){
return new Integer
} elseif(paramLeft instanceof Double){
....
}
I have an assignment where Im supposed to finish the implementation on a generic sparse matrix. Im stuck on the addition part. The matrix is only going to support numbers so I had it extend Number hoping I could then add the numbers, thats wrong. The data structure is NOT an array, it is essentially 2 linked lists. (one for rows and one for columns) Here is the code in question:
public MatrixSparse<? extends Number> addition(MatrixSparse<? extends Number> A, MatrixSparse<? extends Number> B, MatrixSparse<? extends Number> result) {
for (int i = 0; i < r.length; i++) {
for(int j = 0; j < c.length; j++) {
// set (i, j) to the sum of A(i,j) and B(i,j) is giving me an error
// "+" is undefined for type capture#2-? etc.
result.set(i, j, (A.get(i, j) + B.get(i, j)));
}
}
return result;
}
and the class header + class variables:
class MatrixSparse<T extends Number> {
final Links r[];
final Links c[];
final int rows, columns;
final T zero;
any suggestions about how to implement this add method?
Treating then that as a mental/school exercise: You cannot add two generics together with "+" operator - operators are not "genericable" and you cannot overload them in Java (pretty much different than C++) and auto-boxing does not help. The only thing you can do I think is to write a generic T add(T paramLeft,T paramRight) in your Matrix and do something like that:
if (paramLeft instanceof Integer) {
return new Integer(((Integer)paramLeft).intValue()+ ((Integer)paramRight).intValue());
} elseif (paramLeft instanceof Double) {
....
}
这篇关于通用稀疏矩阵加法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!