Initialize a collection within an object?

后端 未结 10 1249
长发绾君心
长发绾君心 2021-02-04 15:03

If an object has a property that is a collection, should the object create the collection object or make a consumer check for null? I know the consumer should not assume, just

10条回答
  •  再見小時候
    2021-02-04 15:38

    I prefer to create the collection upon instantiation, provide add/remove methods in the containing object, and if needed, provide addAll/removeAll methods for adding and removing entire external collections. I never allow the collection object to be accessed for get or set by the caller - I may, however, provide a getter that returns a copy (poss. immutable) of the collection.

    I have also had copy-on-write implementations which provide an immutably wrapped view, since any mutation will create a new underlying collection.

提交回复
热议问题