No, this is not just for reading ... although this is the intention.
Given a List<? extends Number> List<? extends Number> , the compiler converts its type to List<X> , where X is an unknown subtype of Number. Therefore, the object has an add(X) method. We can call a method with argument X ... for example, null .
And since get() returns X , we can also call add() with a value from get() .... Directly calling list.add(list.get(i)) will fail, although that makes sense. We need a little helper .
Classic example: Collections.reverse(List<? extends Object> list) . This method will change the list , despite the wildcard.
You can also call mutating methods such as clear() , of course, on any list.
In this case, the wildcard is mainly intended for use by variance , and most often it conveys the intent of the API developer on whether the type parameter is intended for input or output. For example, declaring List<? super/extends Foo> List<? super/extends Foo> , the API expresses that it intends to enter T in or get T from the list.
This is a misconception that wildcard does read / write only. But this misconception works in most use cases. And the more people have this error, the more it becomes a convention ...
see my article on the template - http://bayou.io/draft/Capturing_Wildcards.html
source share