Create a copy of the collection

I am reading the efficient Java version of J. Bloch, and now I am in the section on avoiding returning nulls, but returning empty collections. This sample code contains a 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 can’t understand what is wrong, only returning cheesesInStockif cheesesInStock.isEmpty(). why is it better to return the predefined Collections.emptyList(). What problems can we get if we return instead cheesesInStock.

+4
source share
5 answers

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

This is not a good practice as you can control the upload process.

+7

  • Collections.emptyList();, .
  • ( )

API, :

(). .

:

 List<String> s = Collections.emptyList();

: List . , , . ( , .)

+5

, , , . , , , String , , .

String getString(){
  return someString; // no need to copy
}

:

  • , .
  • , , .
+5

cheesesInStock , List, , , ( ); , -, , . :

List<Cheese> list = myObject.getCheeseList();
list.add(new Cheese()); // this also affects the list inside myObject

, new ArrayList<Cheese>(previousList). , List List, Collections.unmodifiableList: - .

Collections.emptyList(); new ArrayList<Cheese>(emptyList) , . , Collections.emptyList(); List.

+2
source

The list cheesesInStockcan be structurally modified later, but Collections.emptyList()returns an empty list, which cannot be structurally modified later. Collections.emptyList()returns EmptyListsome of the functions: -

public void add(int index, E element) {
    throw new UnsupportedOperationException();
}
public E get(int index) {
    throw new IndexOutOfBoundsException("Index: "+index);
}
+2
source

Source: https://habr.com/ru/post/1611614/


All Articles