【发布时间】:2011-09-06 20:22:24
【问题描述】:
以下代码给出编译错误:
public void method(List<String> aList) {}
public void passEmptyList() {
method(Collections.emptyList());
}
有没有办法将空列表传递给method而不
- 使用中间变量
- 铸造
- 创建另一个列表对象,例如
new ArrayList<String>()
?
【问题讨论】:
以下代码给出编译错误:
public void method(List<String> aList) {}
public void passEmptyList() {
method(Collections.emptyList());
}
有没有办法将空列表传递给method而不
new ArrayList<String>()
?
【问题讨论】:
替换
method(Collections.emptyList());
与
method(Collections.<String>emptyList());
. 之后的<String> 是emptyList 的类型参数的显式绑定,因此它将返回List<String> 而不是List<Object>。
【讨论】:
你可以像这样指定类型参数:
public void passEmptyList() {
method(Collections.<String>emptyList());
}
【讨论】: