Java generics SuppressWarnings("unchecked") mystery
Posted
by
Johannes Ernst
on Stack Overflow
See other posts from Stack Overflow
or by Johannes Ernst
Published on 2012-12-11T22:43:49Z
Indexed on
2012/12/11
23:03 UTC
Read the original article
Hit count: 310
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)
© Stack Overflow or respective owner