Immutable objects and unmodifiable collections

喜夏-厌秋 提交于 2019-11-29 15:43:20

I'd say if you create Immutable collection then you need to protect yourself from somebody modifying list that was given as an argument to constructor, you should protectively copy it.

public Immutable(List<Integer> values, String hello) {
    this.values = Collections.unmodifiableList(new ArrayList<Integer>(values));
    this.hello = hello;
}

I personally have long ago switched to Guava collections as there you can find interfaces for immutable collections. Your constructor would look like that:

public Immutable(ImmutableList<Integer> values, String hello) {
    this.values = values;
    this.hello = hello;
}

You'd be sure that argument you receive will not be modified by anyone.

It is usually a good idea to keep reference to immutable list within your immutable class as it then guarantees that you don't modify it by mistake.

Case (1) in my opinion makes sense only when factory method is the only way to create the immutable collection and even then it may break when someone refactors these classes. Unless there are other limitations it is always best to create self-sufficient classes.

First of all, your code in all places is indeed immutable but only because an Integer is immutable.
If you had private final List<SomeCustomClass> values; instead, Collections.unmodifiableList(values); would not guarantee that individual SomeCustomClass of the list is immutable. You would have to code for that.
Having said that, another option is to do a defencive deep copy of the list. This approach also offers immutability.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!