How can I instantiate a typical array type in java?

I had a problem creating 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 carry the matrix, that it is a subtype of Number and returns the transpose of the matrix in the specified type. Any help would be greatly appreciated. Thanks.

+4
source share
4 answers

You can use java.lang.reflect.Array to dynamically create an array of a given type. You just need to pass a class object of this desired type, for example:

 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); } 
+4
source

The type does not know at run time, so you cannot use it that way. Instead, you need something like.

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

Note: generics cannot be primitives, therefore you cannot use double[][]

Thanks to @newacct for the suggestion of highlighting in one step.

+4
source

You can use this to simultaneously create both dimensions:

  // 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); 
+2
source

See Is it possible to create an array whose component type is a parametric lookup type? and Can I create an array whose component type is a specific parameterized type? in the Generation Frequently Asked Questions section for a detailed explanation of why you cannot do this.

0
source

Source: https://habr.com/ru/post/1432495/


All Articles