无法投射通用集? [英] Can't cast generic sets?
问题描述
public static class Parent {}
public static class Child extends Parent {}
设置< Child> childs = new HashSet();
Set< Parent>父母=(设置<父>)孩子; //错误:不可兑换的类型
父亲=(父)new Child(); //作品?!
为什么不能像这样工作?我希望隐式转换不会因泛型的各种规则而起作用,但为什么不能进行显式转换呢?
解决方案转换不起作用,因为 Java泛型不是协变 如果编译器允许: 那么在这种情况下会发生什么情况? 最后一行会尝试分配 所有 I'm ran into an interesting issue today. Consider the following code Why wouldn't a cast like that work? I would expect that an implicit cast wouldn't work due to the various rules of generics, but why can't an explicit cast work? The cast doesn't work because Java generics are not covariant. If the compiler allowed this: then what would happen in this case? The last line would attempt to assign All 这篇关于无法投射通用集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
List< ;儿童> children = new ArrayList();
列表< Parent>父母=(列表<父>)子女;
parents.add(new Parent());
Child c = children.get(0);
父
到小孩
—但是父
不是小孩$> c $!
小孩
都是父母
(因为 Child extends Parent
),但所有父母
都不是小孩
。public static class Parent {}
public static class Child extends Parent {}
Set<Child> childs = new HashSet();
Set<Parent> parents = (Set<Parent>)childs; //Error: inconvertible types
Parent parent = (Parent)new Child(); //works?!
List<Child> children = new ArrayList();
List<Parent> parents = (List<Parent>)children;
parents.add(new Parent());
Child c = children.get(0);
Parent
to a Child
— but a Parent
is not a Child
!Child
are Parent
(since Child extends Parent
) but all Parent
are not Child
.