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)?
public List getList() { return Collections.unmodifiableList(list); }
Returns a list that is not modified using the method Collection.unmodifiableList():
Collection.unmodifiableList()
Collections - Collection.unmodifiableList ()
Collections.unmodifiableList(). .
lweller - , , UnsupportOperationException, , , . , UnmodifiableList, List , , , . , couse, Collection.
UnsupportOperationException
UnmodifiableList
List
Collection
, , , . , , , .
, :
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.
, , - .
.
public List getList() { ArrayList copy = new ArrayList(this.list); return Collections.unmodifiableList(copy); }
,
listXXX();
. / .
guava ImmutableList. :
public ImmutableList<T> getMyList() { ImmutableList.copyOf(myList); }
guava Collections.unmodifiableList , , , , - .
Source: https://habr.com/ru/post/1786433/More articles:How to register errors from Xul to a file? - debuggingHow can I hide the evaluation result in Mathematica? - wolfram-mathematicaWhat is the best way to create a large number of unique promo codes? - performanceC ++ Error Reporting Interface - c ++Dynamically adding a command button to a GridView - c #How to make Asp.net recognize a JS form feed as an Ajax request? - ajax"too much recursion" in my rotating banner script - javascriptВерсия для печати страницы. Я хочу добавить полный URL-адрес относительных ссылок - javascriptThe Html collection has .length, but undefined.item (*) - javascriptCan a builder pattern do too much? - javaAll Articles