开发者

Is there a type-safe way to pass an empty list as an argument in java?

开发者 https://www.devze.com 2023-04-02 17:37 出处:网络
The following code gives a compile error: public void method(List<String> aList) {} public void passEmptyList() {

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

精彩评论

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