Any way to make a generic List where I can add a type AND a subtype?

Posted by user383178 on Stack Overflow See other posts from Stack Overflow or by user383178
Published on 2011-01-05T23:35:08Z Indexed on 2011/01/05 23:54 UTC
Read the original article Hit count: 170

Filed under:
|
|
|

I understand why I cannot do the following:

private class Parent {
};

private class Child extends Parent {
};

private class GrandChild extends Child {
};

public void wontCompile(List<? extends Parent> genericList, Child itemToAdd) {
    genericList.add(itemToAdd);
}

My question is there ANY practical way to have a typesafe List where you can call add(E) where E is known to be only a Parent or a Child?

I vaguely remember some use of the "|" operator as used for wildcard bounds, but I cannot find it in the spec...

Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about list