无法投射通用套装?

The*_*eLQ 3 java generics

我今天遇到了一个有趣的问题.请考虑以下代码

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?!
Run Code Online (Sandbox Code Playgroud)

为什么这样的演员不会工作?我希望由于泛型的各种规则,隐式演员不会起作用,但为什么不能进行明确的演员工作呢?

Mat*_*all 16

演员表不起作用,因为Java泛型不是协变的.

如果编译器允许这样:

List<Child> children = new ArrayList();
List<Parent> parents = (List<Parent>)children;
Run Code Online (Sandbox Code Playgroud)

那么在这种情况下会发生什么?

parents.add(new Parent());
Child c = children.get(0);
Run Code Online (Sandbox Code Playgroud)

最后一行会尝试分配ParentChild- 但是a Parent 不是Child!

所有Child都是Parent(因为Child extends Parent)但都不ParentChild.