Collections.unmodifiableList and defensive copy

后端 未结 8 1885
一向
一向 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 05:04

    the API says it internal collections in your case the collection is not internal

    the point is that when you have a private list in class an a gettet for that list, then you may want callers of the getter to not be able to modify the list in witch case you'll have to return an umodifiable list. otherwise the returned list is just a reference to your internal/private list and thus its content can be modified.

    0 讨论(0)
  • 2020-12-13 05:08

    The statement:

    Collections.unmodifiableList(a1);
    

    returns a wrapper over the original collection whose modifier methods throw UnsupportedOperationException.

    The wrapper is read-through, meaning that if you modify a1, the changes reflect on the wrapped collection a2.

    0 讨论(0)
提交回复
热议问题