Generic sparse matrix addition

情到浓时终转凉″ 提交于 2019-12-11 06:18:40

问题


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?


回答1:


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) { 
     ....
}



回答2:


I have three suggestions:

  1. Start writing code. It looks like you posted the skeleton you were already given to start and expect people here to fill it out for you. Post some code and ask a specific question when something goes wrong.
  2. Can you write a successful non-sparse matrix addition? At least you'll have that worked out before you start.
  3. I'd forget about generics until you have something working. Add a matrix of integers or doubles first, then add generics.



回答3:


Why do you want to write your own SparseMatrix? The problem is pretty generic and it is for sure reinventing the wheel if you try to do it yourself. Quick google search shows for example:

http://code.google.com/p/matrix-toolkits-java/

Which is good if LGPL licence is not scaring you away, but I am sure there are plenty of other places you can get ready and tested implementation that will be good for use. I'd rather spend time on finding solution rather than inventing it again.



来源:https://stackoverflow.com/questions/6481083/generic-sparse-matrix-addition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!