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.Array
to dynamically instantiate an Array of a given type. You just have to pass in the Class object of that desired type, something like this:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With