Java Generics – possible bug?

Tags:

This is the contents I’ve already posted to the generics forum of java.sun.com. Until now, I believe that this is a bug, or a lack of feature at the very least. Quite disappointed in java generics. Comments welcome.

You can see my posting at
Developer Forums, Sun Developer Network
comp.lang.java.advocacy

—————————————————-

See the following code:

class A {}

class B {}

public class Test {
    
    public static void main(String[] args) {
        A a = null;
        foo(a);
    }
    
    public static <T> void foo(T a) {

        T[] t = (T[]) new Object[10];
        Object[] o = t; // correct. Object[] is parent of T[].
        o[0] = new B(); // correct. Insert B into object[].
        T val = t[0]; // Type error if T is not A!!
        
        System.out.println(t[0]);
    }
}

T[] t = (T[]) new Object[10]; is the way of declaring an array of T that people in this forum recommend. However, I’ve found something quite strange. As you can see in the code above , T must be A. However, strangely enough, T val = t[0] succeeded. In this code, T is obviously A, and t[0] is also obviously B. However, JDK raises only one warning about T[] t = (T[]) new Object[10], saying that “cast from Object[] to T[] is actually checking against erased type Object[].”

Though the tutorial on generics says that codes are type-safe only when there’s no warning, assigning instance of B into the variable whose type is A is quite weird.

Is this a bug or my mistake?

Comments

Leave a Reply

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