为什么 List<的通用转换?扩展 Set..>列表<设置。>在 Sun JDK 6 上成功,但在 Oracle JDK 7 上编译失败?
下面的代码
class GenericCompilationFailureDemo {
List<? extends GenericCompilationFailureDemo> newList() {
return new ArrayList<GenericCompilationFailureDemo>();
};
void useList() {
List<GenericCompilationFailureDemo> list =
(List<GenericCompilationFailureDemo>) newList();
}
List<? extends Set<GenericCompilationFailureDemo>> newListOfSpecificSets() {
return new ArrayList<Set<GenericCompilationFailureDemo>>();
};
void useListOfSpecificSets() {
List<Set<GenericCompilationFailureDemo>> listOfSpecificSets =
(List<Set<GenericCompilationFailureDemo>>) newListOfSpecificSets();
}
List<? extends Set<? extends GenericCompilationFailureDemo>> newListOfSets() {
return new ArrayList<Set<? extends GenericCompilationFailureDemo>>();
};
void useListOfSet() {
List<Set<? extends GenericCompilationFailureDemo>> listOfSets =
(List<Set<? extends GenericCompilationFailureDemo>>) newListOfSets();
}
}
在 Sun JDK 1.6.0_20 下编译(在 Windows Vista 上为 64 位,但我认为这没有任何区别),但在 Oracle JDK 1.7.0_01(相同平台)下会导致以下编译失败:
[ERROR] src\main\java\GenericCompilationFailureDemo.java:[56,78] error: inconvertible types
请注意,前两个“扩展到特定类型”强制转换,并且在1.7.0_01下仍然成功,因此它似乎与“双泛型扩展”有关。useList
useListOfSpecificSets
任何想法,在6和7之间可能发生了什么变化,以及观察到的行为是根据规范还是错误?
编辑以回应Sanjay的评论:
@Sanjay:啊哈,有趣!此处的输出来自:java -version
java version "1.7.0_01"
Java(TM) SE Runtime Environment (build 1.7.0_01-b08)
Java HotSpot(TM) 64-Bit Server VM (build 21.1-b02, mixed mode)
这里的结果(与上面的代码相同,用于List,ArrayList和Set的import语句):javac GenericCompilationFailureDemo.java
GenericCompilationFailureDemo.java:30: error: inconvertible types
(List<Set<? extends GenericCompilationFailureDemo>>) newListOfSets()
;
^
required: List<Set<? extends GenericCompilationFailureDemo>>
found: List<CAP#1>
where CAP#1 is a fresh type-variable:
CAP#1 extends Set<? extends GenericCompilationFailureDemo> from capture of ?
extends Set<? extends GenericCompilationFailureDemo>
Note: GenericCompilationFailureDemo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error