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

Jev*_*n7x 5 java arrays generics instantiation multidimensional-array

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

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;
}
}
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*rey 5

该类型在运行时是未知的,因此您不能以这种方式使用它。相反,你需要类似的东西。

Class type = matrix.getClass().getComponentType().getComponentType();
T[][] transpose = (T[][]) Array.newInstance(type, rows, cols);
Run Code Online (Sandbox Code Playgroud)

注意:泛型不能是基元,因此您将无法使用double[][]

感谢@newacct 建议您一步分配。


Shi*_*gon 5

您可以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);  
}
Run Code Online (Sandbox Code Playgroud)

  • 不必使用arrayType,因为它可以从matrix中获得。 (2认同)