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
Wrap the return value with java.util.Collections.unmodifiableList. It does not make a copy of the data, but wraps the original list, and delegates read-only operations to the underlying list. Operations which would modify the list are rejected at runtime via UnsupportedOperationException
.
Your
return arrayList;
becomes
return Collections.unmodifiableList(arrayList);
Unfortunately the read-only constraints won't be enforced by the compiler. They will, however, be enforced at runtime.
You also have available to you: unmodifiableSet, unmodifiableMap, unmodifiableCollection, unmodifiableSortedSet, and unmodifiableSortedMap. And if these are not enough, you can still take inspiration from this general design approach, and create your own custom read-only wrapper classes.