I have a Java Class that contains subitems of Objects that extend MyClass.
class MyClass {
List<? extends MyClass> items;
[...]
For some reason I can't insert MyClass items to this list. I don't Understand why, and how I may bypass this issue. For example:
void foo(){
items = new LinkedList<MyClass>(); // This is OK
items.add(new MyClass()); // Not allowed... why?
}
The compiler says "The method add(capture#1-of ? extends MyClass) in the type List is not applicable for the arguments (MyClass)"
I really don't understand how to bypass this issue, and why the compiler should accept only a type which necessarely extends MyClass.
Note: why am I in the need to use this approach? Because I need to allow extension of MyClass to have list of subitems.
List<? extends MyClass> items
means the type parameter is unknown type which is assignable to MyClass
.
For example, it could be a List
of MySubClass
:
public MySubClass extends MyClass{}
List<? extends MyClass> items = new ArrayList<MySubClass>();
Now consider you have MyAnotherSubClass
which extends from MyClass
too:
public MyAnotherSubClass extends MyClass{}
MyClass item = new MyAnotherSubClass(); // refer it using MyClass
Obviously, List<MySubClass>
should not be allowed to contain MyAnotherSubClass
:
items.add(item); // compile error
The declaration
List<? extends MyClass> items;
says that items
is a List
whose type parameter is not exactly known, but is either MyClass
or a subclass.
Re-read that, carefully. It explains why it is not type-safe to add anything to such a List
: its type parameter is unknown. If it happens to be MySubClass1
, then adding a MyClass
or a MySubClass2
is incorrect. If it happens to be MySubClass2
, then adding a MySubClass1
is incorrect. There is no type at all that can safely be added.
If you want a List
to which you can add objects of type MyClass
and also objects of any subclass of MyClass
, then you probably are looking simply for List<MyClass>
.
Technically, a List<? super MyClass>
would also serve that specific purpose, but you would have the opposite problem with that: it would not be type safe to assume the list elements to be any type more specific than Object
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With