开发者

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

  • Using an intermediate variable
  • Casting
  • Creating another list object such as new ArrayList<St开发者_开发百科ring>()

?


Replace

method(Collections.emptyList());

with

method(Collections.<String>emptyList());

The <String> after the . is an explicit binding for emptyList's type parameter, so it will return a List<String> instead of a List<Object>.


You can specify the type param like so:

public void passEmptyList() {
    method(Collections.<String>emptyList());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜