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