4

I'm trying to make my own Matrix class in Java. What I want is to specify the type (float, long, int ...) and size M*N of the Matrix when creating it.

In order to do that, I created the class the following way: public class Matrix<T extends Number> { ...

The problem is that when creating the Array this.m = new T[M][N];, an error occurs saying type parameter 'T' cannot be instantiated directly, I'm guessing because different types take different sizes in the memory.

The only way I could get around this was to do: this.m = (T[][]) new Number[M][N]; But I have no idea if this is a good idea, or if there is a better way to do it.

Here is the complete code:

public class Matrix<T extends Number> {

    /**
     * M represents the Matrix' number of rows.
     * N represents the Matrix' number of columns.
     */
    final private int M, N;

    /**
     * Matrix value.
     */
    private T[][] m;

    /**
     * Create a new Matrix instance.
     *
     * @param M Number of rows
     * @param N Number of columns
     */
    public Matrix(final int M, final int N) {
        this.M = M;
        this.N = N;

        this.m = (T[][]) new Number[M][N];
    }

}

Thank you for any help or clarification on this.

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
Drade
  • 157
  • 10
  • i think what you've done is correcte – gaetan224 Jul 29 '20 at 15:06
  • 2
    The problem is that after type erasure, the compiler doesn't know what T is: that's determined at runtime. However, the array instantiation must be compiled during compile time (for some reason or other, likely the problem starts to show when retrieving elements from it). The cast however is performed during runtime. More information [here](https://stackoverflow.com/q/299998/589259). I don't see anything terribly wrong with the code, sometimes you have to work around the limitations of Java generics. – Maarten Bodewes Jul 29 '20 at 15:06

0 Answers0