When to use Collections.emptyList()?

Asked

Viewed 936 times

3

I thought I’d use

List<Object> lista = Collections.emptyList();

to initialize a list. But when I try to do lista.add(element) I get a UnsupportedOperationException. After researching a little, I saw that this occurs because the object returned by Collections.emptyList() 'and immutable. Therefore, when 'it is appropriate to use Collections.emptyList() instead of

List<Object> lista = new ArrayList<>(); ?

1 answer

7


Consider a method that returns a List<?>, it’s not beautiful (and it doesn’t even make sense) to return null, in addition to increasing the chances of a NullPointerException sprout in the execution of your application. In the real world, either a list is full or empty, right? Normally an empty list is used as a return, for example:

public List<Pessoa> getPessoas(){
   List<Pessoa> pessoas = new ArrayList<>();

   if(hasSomeCondition()){
      // insere alguns objetos à lista 'pessoas'.
   }

   return pessoas;
}

The problem in the above example is that a new object will always be created for return, even if empty and this can be costly. Return a Collections.emptyList() would be more efficient since this method will always return the same instance (Singleton).

Knowing that the method returns a list always, even if empty, avoids checking by null, for example:

public List<Pessoa> getPessoas(){

   if(hasSomeCondition()){
      // Vai retornar uma lista preenchida cada a condição esteja ok.
   }

   return Collections.emptyList();
}
// Ao invés de:
List<Pessoa> pessoas = getPessoas();
if(pessoas != null){
   switch(pessoas.size()){
     // ...
   }
}
// Pode-se chamar sem medo:
switch(getPessoas().size()){
   // ...
}

Besides, it is thread-safe and no need to worry about the type of the generic object. If your method returns a List<Foo>, call for Collections.emptyList() will automatically give you a list of Foo (same as returning Collections.<Foo>emptyList()).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.