Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How may I add `MyClass` to `List<? extends MyClass>` [duplicate]

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.

like image 709
donnadulcinea Avatar asked Dec 18 '22 21:12

donnadulcinea


2 Answers

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
like image 106
xingbin Avatar answered Jan 04 '23 23:01

xingbin


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.

like image 27
John Bollinger Avatar answered Jan 05 '23 01:01

John Bollinger