小孩$> c $!
所有小孩
都是父母
(因为 Child extends Parent
),但所有父母
都不是小孩
。
I'm ran into an interesting issue today. Consider the following code
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?!
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:
List<Child> children = new ArrayList();
List<Parent> parents = (List<Parent>)children;
then what would happen in this case?
parents.add(new Parent());
Child c = children.get(0);
The last line would attempt to assign Parent
to a Child
— but a Parent
is not a Child
!
All Child
are Parent
(since Child extends Parent
) but all Parent
are not Child
.
这篇关于无法投射通用集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!