涉及通配符的赋值的实际应用是什么?

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

这样分配的原因是什么?

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

一旦我们 "upcast" Fruit 容器中的 Apple 容器,我们就无法在其中添加任何东西。

我知道我们可以这样做:

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

然后我们就可以通过Fruit接口来使用fruitContainer持有的元素了。但是,如果我们以后不能添加任何内容,那么实际原因做这样的事情是什么?

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

那条线 whole 可能没有实际用途,但正如你在问题中指出的那样,部分 其中的(List<? extends Fruit> flistnew ArrayList<Apple>())分别具有实际用途。它们既有效又有用,只是不能组合使用(除非您不需要在列表中添加任何内容)。这就是它编译的原因,每个部分都是有效的;这取决于我们,程序员,以合理和有用的方式组合它们。