[英]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.