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