When to use Collections.emptyList ()?

2

I thought about using

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

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

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

    
asked by anonymous 17.10.2017 / 19:26

1 answer

6

Consider a method that returns a List<?> , is not pretty (and does not even make sense) to return null , in addition to increasing the chances of a NullPointerException " to start running your application. In the real world, or a list is full or empty, right? Usually 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. Returning a Collections.emptyList() would be more efficient since this method will always return the same singleton instance.

Knowing that the method returns a list always, even if empty, avoids checking for 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()){
   // ...
}

In addition, it is thread-safe and you do not have to worry about the generic object type. If your method returns a List<Foo> , calling Collections.emptyList() will automatically give you a list of Foo (same as return Collections.<Foo>emptyList() ).

    
17.10.2017 / 20:15