繁体   English   中英

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

[英]How can I instantiate a generic array type in java?

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

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的子类型,并返回指定类型的矩阵的转置。 任何人的帮助将受到高度赞赏。 谢谢。

您可以使用java.lang.reflect.Array动态实例化给定类型的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);  
}

该类型在运行时不知道,因此您不能以这种方式使用它。 相反,你需要像。

Class type = matrix.getClass().getComponentType().getComponentType();
T[][] transpose = (T[][]) Array.newInstance(type, rows, cols);

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

谢谢你@newacct建议你一步分配。

您可以使用它来一次创建两个维度:

    // this is really a Class<? extends T> but the compiler can't verify that ...
    final Class<?> tClass = matrix.getClass().getComponentType().getComponentType();
    // ... so this contains an unchecked cast.
    @SuppressWarnings("unchecked")
    T[][] transpose = (T[][]) Array.newInstance(tClass, cols, rows);

请参阅是否可以创建其组件类型为通配符参数化类型的数组? 我可以创建一个组件类型是具体参数化类型的数组吗? 从泛型常见问题解答中详细解释了为什么你不能这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM