I have an assignment where Im supposed to finish the implementation on a generic sparse matrix. Im stuck on the addition part. The mat开发者_C百科rix 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) {
....
}
I have three suggestions:
- 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.
- Can you write a successful non-sparse matrix addition? At least you'll have that worked out before you start.
- I'd forget about generics until you have something working. Add a matrix of integers or doubles first, then add generics.
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.
精彩评论