Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

?

like image 688
tb189 Avatar asked Sep 06 '11 20:09

tb189


People also ask

How do you handle an empty list in Java?

The isEmpty() method of List interface in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.

How do you represent an empty list in Java?

To represent an Empty List in Java (an ArrayList is a List), we use java. util. Collections. emptyList() .

How do you pass an empty array list in java?

motif=new ArrayList(); will make the passed arraylist motif to be new instance of arraylist, and thus since its new , its empty. I have not use motif or number. Mot is string arraylist in another class (NewJFrame). When I call it in another class i-e with j.


2 Answers

You can specify the type param like so:

public void passEmptyList() {
    method(Collections.<String>emptyList());
}
like image 20
sblundy Avatar answered Sep 24 '22 05:09

sblundy


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>.

like image 94
Mike Samuel Avatar answered Sep 24 '22 05:09

Mike Samuel