1

I am implementing a Matrix class from scratch with Java language and I am quite new to java. Right now I have an interface of Matrix like this:

public interface Matrix <T extends Number & Comparable<? super T>,L extends List<T>,M extends Matrix>{
    // ... a bunch of methods ...
    public M add(M matrix) throws MatrixException;
    public M mul(M matrix) throws MatrixException;
}

The MatrixException here is an Exception defined by me and List here is also an List class implemented by myself. I also have a DenseMatrix class which extends interface Matrix:

public class DenseMatrix<T extends Number & Comparable<? super T>, L extends List<T>> implements Matrix<T, L, DenseMatrix<T, L>> {
    // ... a bunch of methods ...
    public DenseMatrix<T, L> add(DenseMatrix<T, L> matrix) throws DataStructureException {
    // add two matrix element-wisely
    }
}

But the fact I found is I can't just add two Number together and there's no overload of operator +.

So I have seen solutions like check if the class type of an element in matrix is an instanceof Integer or Double or Long or Float and I have also seen solutions like giving up on using generics but implement methods with respect to all types of Number. But from my perspective neither of these solutions are decent enough like what I can do in C++.

Thus my question is how can I resolve this issue decently? or maybe my design paradigm is completely wrong? If there's a better design, please tell me! Many thanks in advance!

Duo Zhang
  • 11
  • 3
  • Perhaps each element of the matrix is an `Element`, which wraps a `Number`. At the time of an `Element` construction, the concrete `Number` type is known, so some implementation of a `MatrixOp` interface is injected, where the implementation knows how to do add/multiply on that `Number` type. – Andrew S Jan 23 '23 at 23:05

0 Answers0