Java – cannot convert generic set?

I have an interesting problem 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 can't such actors work? I hope that due to the various rules of generics, implicit actors will not work, but why not do explicit actor work?

Solution

The cast doesn't work because Java genetics are not covariant

If the compiler allows this:

List<Child> children = new ArrayList();
List<Parent> parents = (List<Parent>)children;

So what happens in this case?

parents.add(new Parent());
Child c = children.get(0);

The last line attempts to assign a parent to a child – but the parent is not a child!

All children are parents (because children extend parents), but all parents are not children

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>