类中未知类型的数组实例化

时间:2020-07-29 14:59:39

标签: java arrays matrix instantiation

我正在尝试用Java创建自己的Matrix类。 我想要的是在创建float时指定其类型(longintM*N ...)和大小Matrix

为此,我通过以下方式创建了该类:public class Matrix<T extends Number> { ...

问题是创建数组this.m = new T[M][N];时发生错误,提示type parameter 'T' cannot be instantiated directly,我猜是因为不同的类型在内存中的大小不同。

我唯一可以解决此问题的方法是:this.m = (T[][]) new Number[M][N]; 但是我不知道这是一个好主意,还是有更好的方法。

这是完整的代码:

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];
    }

}

谢谢您的帮助或澄清。

0 个答案:

没有答案