Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I instantiate a generic array type in java?

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.

like image 325
Jevison7x Avatar asked Sep 05 '12 14:09

Jevison7x


1 Answers

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);  
}
like image 193
Shivan Dragon Avatar answered Oct 26 '22 20:10

Shivan Dragon