【问题标题】:A class attribute type of List which is not modifiable by accessorList 的类属性类型,访问者不可修改
【发布时间】:2014-05-03 23:04:08
【问题描述】:

考虑以下类:

class Foo
{
  private List<Integer> all;
  private Set<Integer> distinct;
  public List<Integer> getAll()
  {
    return all;
  }
  public void add(Integer i)
  {
    all.add(i);
    distinct.add(i);
  }
}

我不希望 bar 被这样修改:

foo.getAll().add(3);

相反,我想强制执行我自己的add() 程序。
有没有办法做到这一点?

【问题讨论】:

  • 什么是酒吧?此代码会引发编译错误。
  • 我改了。感谢您的通知。

标签: java getter-setter accessor mutators


【解决方案1】:

您可以让getAll() 返回unmodifiable list。你可以认为它是在返回一个视图,所以列表只会处于只读模式。

任何尝试修改返回列表的调用都会抛出UnsupportedOperationException

public List<Integer> getAll(){
    return Collections.unmodifiableList(all);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    相关资源
    最近更新 更多