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.