Returning const reference of an arraylist

后端 未结 4 1734
小鲜肉
小鲜肉 2021-02-19 04:22

I really admire java features and I don\'t want to give up using it for the next problem:

I have a class that might be inherited, and inside of it is a private Arr

4条回答
  •  旧巷少年郎
    2021-02-19 04:48

    :) You have several options:

    • Don't expose getter, provide only methods which are allowed to call, e.g.

      public void addToList(Object arg) { this.arr.add(arg);}

    • Return immutable object:

      public List getArr() { return Collections.unmodifiableList(this.arr); }

提交回复
热议问题