Java 不兼容类型:SomeX无法转换为CAP#1
我不明白这里出了什么问题Java 不兼容类型:SomeX无法转换为CAP#1,java,generics,Java,Generics,我不明白这里出了什么问题 import java.util.*; class Main { private static class SomeX {} void doSomethingWithX(SomeX someX) { Collection<? extends SomeX> colectionOfX = new ArrayList<>(); colectionOfX.add(someX); } } 据我所
import java.util.*;
class Main {
private static class SomeX {}
void doSomethingWithX(SomeX someX) {
Collection<? extends SomeX> colectionOfX = new ArrayList<>();
colectionOfX.add(someX);
}
}
据我所知,将第1章的下限扩展到SomeX
,并且SomeX
本身应满足该限制
怎么了?(使用javac1.8.0_102
编译)如果要允许collectionofx
包含SomeX
的任何实例,应声明为:
Collection<SomeX> colectionOfX = new ArrayList<>();
collectionofx=newarraylist();
当你宣布它为
Collection<? extends SomeX> colectionOfX = ...;
Collection所以,这个问题实际上已经在“”中得到了回答,但谷歌搜索并没有带来匹配
就我所知,简短的回答如下:
class Main {
private static class SomeX {}
private static class SomeY extends SomeX {}
void doSomethingWithX(SomeX someX) {
Collection<? extends SomeX> colectionOfX = new ArrayList<SomeY>();
colectionOfX.add(someX);
}
}
主类{
私有静态类SomeX{}
私有静态类SomeY扩展了SomeX{}
void doSomethingWithX(SomeX SomeX){
集合所以……所有这些都不能回答“为什么我不能将SomeX的实例添加到Collection@XtraCoder正如我试图解释的,Collection
class Main {
private static class SomeX {}
private static class SomeY extends SomeX {}
void doSomethingWithX(SomeX someX) {
Collection<? extends SomeX> colectionOfX = new ArrayList<SomeY>();
colectionOfX.add(someX);
}
}