0

我有一个带有 getter 的类,它返回其私有字段 List。

Class MyClass {
  private List<String> myList;

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

但是 getter 方法的调用者不能在该列表中添加或删除元素。

MyClass instance = new MyClass();
List<String> hisList = instance.getMyList();
hisList.add("new element");

引发了 UnsupportedOperationException。

我知道 getter 返回对该列表的引用,但为什么该列表在调用方是只读的?注意我没有在 getter 中返回 Collections.unmodifiableList() 。

更新:

抱歉,我通过 Arrays.asList 创建了一个固定大小的列表,这就是为什么 ;)

4

2 回答 2

4

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

于 2011-02-25T16:14:09.777 回答
4

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

于 2011-02-25T16:22:29.773 回答