Search code examples
javagenericssparse-matrix

Generic sparse matrix addition


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?


Solution

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