【发布时间】:2012-05-07 17:49:03
【问题描述】:
这是jdk1.7.0_04。
我试图使用 Collections.emptyList() 而不是 new 在条件中添加我自己的空列表:
List<String> list = (anArray != null) ? Arrays.asList(anArray) : Collections.emptyList();
但得到以下错误:
error: incompatible types
List<String> list = (anArray != null) ? Arrays.asList(anArray) : Collections.emptyList();
^
required: List<String>
found: List<CAP#1>
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ? extends Object
1 error
我能够确定我需要将事情更改为:
List<String> list = (anArray != null) ? Arrays.asList(anArray) : Collections.<String>emptyList();
但作为工作的一部分,我遇到了奇怪的(对我来说,无论如何)情况:
List<String> alwaysEmpty = Collections.emptyList();
编译正常,但是:
List<String> alwaysEmpty = (List<String>) Collections.emptyList();
给出以下编译错误:
error: inconvertible types
List<String> alwaysEmpty = (List<String>) Collections.emptyList();
^
required: List<String>
found: List<Object>
什么鬼??
现在我可以理解,也许由于某种奇怪的原因,条件运算符的使用会以某种方式阻止类型推断系统意识到emptyList() 调用的类型参数应该是String,因此需要明确指定的。但是为什么插入一个(诚然是多余的)演员会搞砸呢?
【问题讨论】:
标签: java generics collections