5

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

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 的子类型,并返回指定类型的矩阵的转置。任何人的帮助将不胜感激。谢谢。

4

4 回答 4

5

类型在运行时是不知道的,所以你不能这样使用它。相反,您需要类似的东西。

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

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

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

于 2012-09-05T14:15:13.733 回答
5

您可以使用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);  
}
于 2012-09-05T14:16:59.333 回答
2

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

    // 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);
于 2012-09-05T14:20:12.860 回答
0

请参阅我可以创建一个组件类型为通配符参数化类型的数组吗?我可以创建一个组件类型为具体参数化类型的数组吗? 从泛型常见问题解答中获取有关您为什么不能这样做的详细说明。

于 2012-09-05T14:14:17.953 回答