Collections.unmodifiableList and defensive copy

后端 未结 8 1993
一向
一向 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.

提交回复
热议问题