I have a problem with instantiating a generic type array, here is my code:
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;
}
}
I just want this method to be able to transpose a matrix that it’s class is a subtype of Number and return the transpose of the matrix in the specified type. Anybody’s help would be highly appreciated. Thanks.
You can use
java.lang.reflect.Arrayto dynamically instantiate an Array of a given type. You just have to pass in the Class object of that desired type, something like this: