为什么在java中不允许将子类对象的子类集合强制转换为其超类对象的超类集合?
守则亦载于为什么在java中不允许将子类对象的子类集合强制转换为其超类对象的超类集合?,java,generics,Java,Generics,守则亦载于 a包; 导入java.util.List; 公共接口容器{ List getThings(); } 公共级集装箱集装箱{ 公共容器getThingContainer(){ 返回新的ThingContainer(); } } 公共类ThingContainer实现容器{ @凌驾 公共列表getThings(){ 返回null; } } 公共类事物{ } b包 package b; import java.util.List; public class ContainerContai
a包;
导入java.util.List;
公共接口容器{
List getThings();
}
公共级集装箱集装箱{
公共容器getThingContainer(){
返回新的ThingContainer();
}
}
公共类ThingContainer实现容器{
@凌驾
公共列表getThings(){
返回null;
}
}
公共类事物{
}
b包
package b;
import java.util.List;
public class ContainerContainer extends a.ContainerContainer {
ThingContainer<Thing> thingContainer = new ThingContainer<Thing>();
@SuppressWarnings("unchecked")
public a.Container<a.Thing> getContainer() {
return (a.Container<a.Thing>)(Object)thingContainer; //YUCK
}
}
public class ThingContainer<T extends a.Thing>
implements a.Container<T> {
@Override
public List<T> getThings() {
return null;
}
}
public class Thing extends a.Thing {
}
b包;
导入java.util.List;
公共类ContainerContainer扩展了a.ContainerContainer{
ThingContainer ThingContainer=新ThingContainer();
@抑制警告(“未选中”)
公共a.容器getContainer(){
return(a.Container)(Object)thingContainer;//恶心
}
}
公共类货柜
实现一个容器{
@凌驾
公共列表getThings(){
返回null;
}
}
公共类事物扩展了a.事物{
}
我的问题是,当b.ThingContainer是a.ThingContainer的子类,并且它包含的东西是a.Thing的子类时,为什么我必须强制b.ThingContainer(上面标记为YUCK)让我们考虑一个更简单的例子,删除所有无关的细节。(这里,我们将使用
b.Thing
而不是String
,我们将使用a.Thing
而不是Object
;String
是Object
的子类,因此它是类似的。我们将使用a.Container
而不是List
。容器的子类是不相关的,正如您将使用的那样e、 )如果你能理解为什么这个例子不起作用,你就会理解你的问题
List<String> foo = new ArrayList<String>();
List<Object> bar = foo; // why doesn't this work?
List foo=new ArrayList();
列表栏=foo;//为什么这样不行?
我想这回答了你的问题+1对于一个写得好的问题-1.不首先搜索答案;net:0感谢@madth3,是的,特别是感谢@Jim Garrison的链接,我确实搜索过,但我找到的答案是相反的问题。很抱歉,我不确定没有经验的人是否会通过这两行代码更好地理解您的示例。因为bar现在可以接受可能通过foo错误访问的整数。谢谢@newacct
List<String> foo = new ArrayList<String>();
List<Object> bar = foo; // why doesn't this work?