Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a copy of a collection

I'm reading J. Bloch's effective Java and now I'm at the section about avoiding returning nulls, but returning empty collections. This's the code example form the section:

// The right way to return a copy of a collection
public List<Cheese> getCheeseList() {
  if (cheesesInStock.isEmpty())
    return Collections.emptyList(); // Always returns same list
  else
    return new ArrayList<Cheese>(cheesesInStock);
}

I really cannot understand what's wrong with just returning the cheesesInStock if cheesesInStock.isEmpty(). why is it better to return the predefined Collections.emptyList(). What kind of troubles we may get into, if we return cheesesInStock instead.

like image 329
St.Antario Avatar asked Nov 30 '22 10:11

St.Antario


1 Answers

If the method returns cheesesInStock - the caller may add some cheese to the list.

It is a bad practice as you may want to control adding procedure.

like image 116
BobTheBuilder Avatar answered Dec 09 '22 11:12

BobTheBuilder