Search code examples
javagenericsvariable-assignmentcovarianceupcasting

What is the practical application of an assignment involving a wildcard?


what is the reason of an assignment like this?

List<? extends Fruit> flist = new ArrayList<Apple>();
// flist.add(new Apple()); 
// flist.add(new Fruit()); 
// flist.add(new Object());

Once we "upcast" the Apple container in a Fruit container, we are not able to add anything in it.

I know we could do something like:

List<Apple> basket = new ArrayList<Apple>();
//Fill the basket with tons of juicy apples
List<? extends Fruit> fruitContainer = basket;

And then we could be able to use the Fruit interface to use the elements held by fruitContainer. But what can be the practical reason to do something like this, if we cannot add anything later?

List<? extends Fruit> flist = new ArrayList<Apple>();

Solution

  • That line taken a whole probably has no practical use, but as you've noted in your question, each of the the parts of it (List<? extends Fruit> flist and new ArrayList<Apple>()), separately, has a practical use. They're both valid, and useful, just not in combination (unless you don't need to put anything in your list). That's why it compiles, each of the parts is valid; it's up to us, the programmers, to combine them in a reasonable and useful way.