Search code examples
javalistgenericsbounded-wildcard

List<? extends MyType>


I have a Java question about generics. I declared a generic list:

List<? extends MyType> listOfMyType;

Then in some method I try instantiate and add items to that list:

listOfMyType = new ArrayList<MyType>();
listOfMyType.add(myTypeInstance); 

Where myTypeInstance is just an object of type MyType; it won't compile. It says:

The method add(capture#3-of ? extends MyType) in the type List<capture#3-of ? extends MyType> is not applicable for the arguments (MyType)

Any idea?


Solution

  • You cannot do a "put" with extends . Look at Generics - Get and Put rule.