lundi 23 janvier 2023

Java: How to add two generics of java.lang.Number in a function and design pattern of Matrix in Java?

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!

Aucun commentaire:

Enregistrer un commentaire