Alex Rivera | Logout

Java generics SuppressWarnings("unchecked") mystery

Asked 2012-12-11T22:43:49.150
11

Why does code alternative(1) compile without warnings, and code alternative(2) produce an "unchecked cast" warning?

Common for both:

class Foo<T> {
    Foo( T [] arg ) {
    }
}

Alternative (1):

class Bar<T> extends Foo<T> {
    protected static final Object [] EMPTY_ARRAY = {};

    @SuppressWarnings("unchecked")
    Bar() {
         super( (T []) EMPTY_ARRAY );
    }
}

Alternative (2):

class Bar<T> extends Foo<T> {
    @SuppressWarnings("unchecked")
    Bar() {
         super( (T []) EMPTY_ARRAY );
    }

    protected static final Object [] EMPTY_ARRAY = {};
}

Alternative (2) produces:

javac -Xlint:unchecked Foo.java Bar.java 
Bar.java:4: warning: [unchecked] unchecked cast
             super( (T []) EMPTY_ARRAY );
                           ^
  required: T[]
  found:    Object[]
  where T is a type-variable:
    T extends Object declared in class Bar
1 warning

This is:

java version "1.7.0_07"
Java(TM) SE Runtime Environment (build 1.7.0_07-b10)
Java HotSpot(TM) 64-Bit Server VM (build 23.3-b01, mixed mode)
Edit
Report

1 Answer

3

I'm able to emulate this strange behaviour on my Windows 7 64b machine with:

  • Java(TM) SE Runtime Environment (build 1.7.0_02-b13)
  • OpenJDK Runtime Environment (build 1.8.0-ea-lambda-nightly-h1669-20121030-b63-b00)

Which means both the OpenJDK and the Oracle JDK are affected, both JDK7 and JDK8 (yes, you can already download it).

Eclipse, since it uses its own JDT compiler, doesn't have this problem.

So it seems that this is indeed a javac bug. If you report it, please keep me updated.

EDIT:

I've also located a JDK6 installation on my computer, so I tried that one and actually, it works without a warning in both cases, which is the correct behaviour:

  • Java(TM) SE Runtime Environment (build 1.6.0_23-b05)

Although my Windows are 64b, all the said JDKs are only 32b.

answered 2012-12-11T23:38:55.323

Your Answer