Why is it better to return unmodifiableList from a method where list is created?

linuxNoob :
 public List<Integer> getInts()
{
    List<Integer> xs = new ArrayList<Integer>();
    xs.add(1);
    // return Collections.unmodifiableList(xs);
    return xs;
}   

I understand that returning an unmodifiable list will prevent the consumer from adding additional elements to the list reference but apart from that what am I gaining here by wrapping it in an unmodifiable list? I am creating a new list every time the method is invoked.

Bohemian :

When an object returns a mutable private field, it is exposed to unwanted/unknown alteration of its internal state by external agents, which violates encapsulation.

The pattern to which you refer, called safe publishing, protects against this problem. It can be accomplished by returning either a deep copy, or the field (and any mutable sub-fields) in an immutable wrapper.

In the case of your commented out code:

return Collections.unmodifiableList(xs);

it is creating a new object, but it just a very thin layer on top of the list and you would barely be able to measure the cpu or memory performance cost of doing it.

You can also:

return new ArrayList<>(xs);

to make a deep copy (in this case, because Integer is immutable).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110739&siteId=1