为什么代码替代(1)编译时没有警告,而代码替代(2)会产生“未经检查的强制转换”警告?
两者的共同点:
class Foo<T> {
Foo( T [] arg ) {
}
}
备选方案 (1):
class Bar<T> extends Foo<T> {
protected static final Object [] EMPTY_ARRAY = {};
@SuppressWarnings("unchecked")
Bar() {
super( (T []) EMPTY_ARRAY );
}
}
备选方案 (2):
class Bar<T> extends Foo<T> {
@SuppressWarnings("unchecked")
Bar() {
super( (T []) EMPTY_ARRAY );
}
protected static final Object [] EMPTY_ARRAY = {};
}
备选方案 (2) 产生:
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
这是:
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)