Collections.unmodifiableList and defensive copy

后端 未结 8 1987
一向
一向 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:48

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

    Typically, you would use it that way:

    private List a1 = Arrays.asList(1, 2, 3);
    
    public List getUnmodifiable() {
        return Collections.unmodifiableList(a1);
    }
    

    Someone who calls getUnmodifiable and does not have access to the internal of your class (i.e. they can't acces the private variable a1), won't be able to modify the returned list.

提交回复
热议问题