Collections.unmodifiableList and defensive copy

后端 未结 8 1957
一向
一向 2020-12-13 04:30

If I write

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

a2 is r

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 04:43

    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 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).

提交回复
热议问题