Creating an array whose component is concrete parameterized type.

Tags:

What do you think will happen when following code is compiled in JDK 5.0?

T matrix[][] = null;
matrix = new T[10][10];

Contrary to your intuition, it simply fails. The reason behind this is that the type information of T is not maintained during runtime. (FYI, generics in JAVA is nothing but a casting which is commonly called erasure.) Such a decision was made for backward compatability.

So, to create a generic two dimensional array:

public class Matrix<T> {
    
    T matrix[][];

    public Matrix(Class<T> cls, int width, int height) {
        for (int i = 0; i < height; i++) {
            matrix[i] = (T[]) Array.newInstance(cls, width);
        }
    }
}

When the code above is compiled, javac will complain that ‘The cast from Object to T[] is actually checking the erased type Object[].’ This error can’t be avoided because of backward compatability. (arrrgh…) Array.newInstance was decided to return Object as it did in previous releases. Hence, though we are passing Class<T>, Array class automatically erases type information and returns Object.

There’s a way, however, to suppress warnings. Let me show you another example:

@SuppressWarnings(“unchecked”)
public Matrix(Class cls, int width, int height) {
    fMatrix = (T[][]) new Object[height][width];
}

The annotation ‘SuppressWarnings’ removes the warnings. Note the way how T[][] array was initialized.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *