Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections.unmodifiableList and defensive copy

If I write

List<Integer> a1 = Arrays.asList(1, 2, 3); List<Integer> a2 = Collections.unmodifiableList(a1); 

a2 is read-only but if I write

a1.set(0,10); 

then a2 is also modified.

If in the API is said:

Returns an unmodifiable view of the specified collection. This method allows modules to provide users with "read-only" access to internal collections.

then, why if I modify the original collection also the target-copied collection is modified?

Maybe did I misunderstand the meaning and if so what's the way to write a defensive copy of that collection?

like image 874
xdevel2000 Avatar asked Feb 27 '13 11:02

xdevel2000


People also ask

What does collections unmodifiableList do?

The unmodifiableList() method of java. util. Collections class is used to return an unmodifiable view of the specified list. This method allows modules to provide users with “read-only” access to internal lists.

How do you make an unmodifiableList modifiable in Java?

The solution to this problem is quite simple and is highlighted in the following code. final List<String> modifiable = new ArrayList<>(); modifiable. add("Java"); modifiable. add("is"); // Here we are creating a new array list final List<String> unmodifiable = Collections.


1 Answers

Yes, you understood it correctly. The idea is that the object returned by umodifiableCollection can't directly be changed, but could change through other means (effectively by changing the internal collection directly).

As long as something has access to the internal list, the "unmodifiable" collection could be changed.

That's why you usually construct a unmodifiable collection and make sure that nothing can ever get to the internal list:

Collection<Integer> myUmodifiableCollection = Collection.umodifiableCollection(Arrays.asList(1, 2, 3)); 

Since nothing ever gets a reference to the List created by asList, this is a truly unmodifiable collection.

The advantage of this approach is that you don't need to copy the original collection/list at all, which avoids using memory and computing power.

Guava provides the ImmutableCollection class (and its subclasses such as ImmutableList) which provide true immutable collections (usually by copying the source).

like image 129
Joachim Sauer Avatar answered Oct 02 '22 22:10

Joachim Sauer