6

我得到“类型不匹配:无法转换List<CherryCoke>List<Coke<?>>

看起来“樱桃可乐清单”不是“可乐清单”。这是违反直觉的。无论如何,如果它必须是 aList<Coke<?>>并且我必须有一个子类,我怎么能创建那个'xs' Coke<Cherry>

class Taste { }
class Cherry extends Taste { }

abstract class Coke<T extends Taste> { }    

class CherryCoke extends Coke<Cherry> { }

class x {
  void drink() {
    List<Coke<?>> xs = Arrays.asList(new CherryCoke());
  }
}
4

3 回答 3

9

你是对的——“可乐列表”不是“樱桃可乐列表”——“扩展可乐的东西”列表是“樱桃可乐列表”。

您可能想定义xsList <? extends Coke<?>> xs = Arrays.asList(new CherryCoke());

于 2012-11-15T00:14:21.820 回答
5

As others have pointed out, List<CherryCoke> and List<Coke<?>> are not the same thing.

But that's not really the issue here. It's not necessary to type xs as List<? extends Coke<?>>. You could have just as well created a new List<Coke<?>> and then added a new CherryCoke to it.

The error simply has to do with the compiler inferring asList's type parameter T incorrectly. If you specify T yourself it compiles:

List<Coke<?>> xs = Arrays.<Coke<?>>asList(new CherryCoke());
于 2012-11-15T00:44:03.130 回答
4
List<Coke<?>> xs = Arrays.asList(new CherryCoke());

List<CherryCoke>不是List<Coke<?>>(List of Coke of anything) 的子类型。

你应该定义你的泛型类型的上限。

List<? extends Coke<?>> xs = Arrays.asList(new CherryCoke());
于 2012-11-15T00:18:42.917 回答