简体   繁体   中英

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<String>()

?

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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