Is it a bad practice to add elements to List using getter method in java?

前端 未结 6 2099
北海茫月
北海茫月 2020-12-15 20:44

Suppose I have a private ArrayList or a LinkedList inside a class, that I will never assign new reference to it, or in other words this will never

6条回答
  •  太阳男子
    2020-12-15 21:23

    In general, you should not assume that the list being returned by the getter is the original one. It could be decorated or proxied for example. If you want to prevent that a new list is set on the target object, you could define an add method on the target class instead.

提交回复
热议问题