Can't use shared sets?

Today I ran into an interesting problem. 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 not make such a throw? I would expect that an implicit cast will not work due to different generic rules, but why doesn't explicit cast work?

+3
source share
4 answers

The cast does not work because Java Generators are not covariant .

If the compiler allowed this:

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

what will happen in this case?

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

The last line will try to appropriate Parent Child- but Parent not Child!

All Childare Parent(since Child extends Parent), but all are Parentnot Child.

+16
source

A Set<Parent> Parent. A Set<Child> Child. , Parent, Child, , , .

+1

(sic) . () , .

+1

, -:

Set<Child> childs = new HashSet();
Set<? extends Parent> parents = childs;

Set - Set

, , , . , , . , , , , , , , , , , . - , : (, ) (/).

:

Parent parent = new Child(); 

Stéphane

+1

All Articles