If you use Eclipse Collections , you can change the type of MyImmutableClass.data
to ImmutableList
.
class MyImmutableClass { private ImmutableList<Integer> data; public MyImmutableClass(List<Integer> data) { this.data = Lists.immutable.withAll(data); } public ListIterable<Integer> getData() { return data; } }
The types Eclipse Collection ImmutableList
and ListIterable
are immutable by contract, that is, they do not have the add()
and remove()
methods. Thus, the return type of getData()
shows that the returned list cannot be changed.
Both ImmutableList
and MutableList
extend ListIterable
, so you can change the implementation from ImmutableList
to an unmodifiable list without changing the API.
class MyImmutableClass { private MutableList<Integer> data; public MyImmutableClass(List<Integer> data) { this.data = Lists.mutable.withAll(data); } public ListIterable<Integer> getData() { return data.asUnmodifiable(); } }
Note. I am a committer for Eclipse collections.
source share