如何在Java中实例化通用数组类型?

Jevison7x:

我在实例化泛型类型数组时遇到问题,这是我的代码:

public final class MatrixOperations<T extends Number>
{
    /**
 * <p>This method gets the transpose of any matrix passed in to it as argument</p>
 * @param matrix This is the matrix to be transposed
 * @param rows  The number of rows in this matrix
 * @param cols  The number of columns in this matrix
 * @return The transpose of the matrix
 */
public T[][] getTranspose(T[][] matrix, int rows, int cols)
{
    T[][] transpose = new T[rows][cols];//Error: generic array creation
    for(int x = 0; x < cols; x++)
    {
        for(int y = 0; y < rows; y++)
        {
            transpose[x][y] = matrix[y][x];
        }
    }
    return transpose;
}
}

我只希望此方法能够转置其类为Number的子类型的矩阵并返回指定类型的矩阵的转置。任何人的帮助将不胜感激。谢谢。

Shivan Dragon:

您可以java.lang.reflect.Array用来动态实例化给定类型的数组。您只需要传入所需类型的Class对象即可,如下所示:

public T[][] getTranspose(Class<T> arrayType, T[][] matrix, int rows, int cols)
{

    T[][] transpose = (T[][]) Array.newInstance(arrayType, rows,cols);
    for (int x = 0; x < cols; x++)
    {
        for (int y = 0; y < rows; y++)
        {
            transpose[x][y] = matrix[y][x];
        }
    }
    return transpose;
}

public static void main(String args[]) {
    MatrixOperations<Integer> mo = new MatrixOperations<>();
    Integer[][] i = mo.getTranspose(Integer.class, new Integer[2][2], 2, 2);
    i[1][1] = new Integer(13);  
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章