[英]Is there a type-safe way to pass an empty list as an argument in java?
The following code gives a compile error: 以下代码给出了编译错误:
public void method(List<String> aList) {}
public void passEmptyList() {
method(Collections.emptyList());
}
Is there a way to pass an empty list to method
without 有没有办法将空列表传递给method
而没有
new ArrayList<String>()
创建另一个列表对象,例如new ArrayList<String>()
? ?
Replace 更换
method(Collections.emptyList());
with 同
method(Collections.<String>emptyList());
The <String>
after the .
之后的<String>
.
is an explicit binding for emptyList
's type parameter, so it will return a List<String>
instead of a List<Object>
. 是emptyList
的类型参数的显式绑定,因此它将返回List<String>
而不是List<Object>
。
You can specify the type param like so: 您可以像这样指定类型参数:
public void passEmptyList() {
method(Collections.<String>emptyList());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.