gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:28:00 25 4
gpt4 key购买 nike

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

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 动态实例化给定类型的数组。您只需传入所需类型的 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);
}

关于java - 如何在 java 中实例化通用数组类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12283384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com