Recipients and setters and container objects (ArrayList, HashMap, etc.)

Say you have a domain class that has an ArrayList attribute. What is the best practice when writing getters and setters for this type of instance (to avoid changing it)?

+3
source share
8 answers
public List getList() {
  return Collections.unmodifiableList(list);
}
+6
source

Returns a list that is not modified using the method Collection.unmodifiableList():

Collections - Collection.unmodifiableList ()

+2
source

lweller - , , UnsupportOperationException, , , . , UnmodifiableList, List , , , . , couse, Collection.

+1

, , , . , , , .

, :

return Collections.unmodifiableList(new ArrayList<Thing>(things));
    // Bit big - shame there isn't a single method and class to do this.

return new ArrayList<Thing>(things);
    // Do you really want to see client code modifying the list?

return Collections.unmodifiableList(things);
    // Client may expecting a snapshot, modifications to the original will mess up.

, , - .

+1

.

public List getList() {
    ArrayList copy = new ArrayList(this.list);
    return Collections.unmodifiableList(copy);
}
+1

,

listXXX(); 

. / .

+1

guava ImmutableList. :

public ImmutableList<T> getMyList() {
  ImmutableList.copyOf(myList);
}

guava Collections.unmodifiableList , , , , - .

+1

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


All Articles