简体   繁体   English

是否有一种类型安全的方法将空列表作为参数传递给java?

[英]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而没有

  • Using an intermediate variable 使用中间变量
  • Casting 铸件
  • Creating another list object such as 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM