开发者

Why cannot I change a collection returned by getter?

开发者 https://www.devze.com 2023-02-13 05:46 出处:网络
I have a class with a getter that returns its private field List. Class MyClass { private List<String> myList;

I have a class with a getter that returns its private field List.

Class MyClass {
  private List<String> myList;

  public List<String> getMyList(){
    return myList;
  }
}

But the caller of the getter method cannot add or remove elements from that List.

MyClass instance = new MyClass();
List<String>开发者_如何学编程; hisList = instance.getMyList();
hisList.add("new element");

UnsupportedOperationException was thrown.

I know that getter returns a reference to that list, but why is that list read-only at caller side? Note I have not returned Collections.unmodifiableList() in the getter.

UPDATE:

Sorry, I created a fix-sized list by Arrays.asList, that why ;)


No, you haven't called unmodifiableList() in the getter, but the list could already be unmodifiable as referenced by myList.

It would help if you could provide a short but complete example (e.g. one which populates myList :)


You are probably creating an unmodifiable or constant List as in:

myList = Arrays.asList("a", "b", ...);  // returns a fixed-size list

only guessing without seeing the code that creates the List...

0

精彩评论

暂无评论...
验证码 换一张
取 消