I just recognized something I do not yet fully know if it is true.
Consider the following code:
final class ImmutableClass {
private int value;
ImmutableClass(int i) {
value = i;
}
int get() {
return value;
}
}
final class MyClass {
private List<ImmutableClass> someList = new ArrayList<AnyImmutableClass>();
//...some methods and constructor
List<? extends ImmutableClass> getSomeList() {
return someList;
}
}
This is an easy way of making references on lists immutable, although the original list is not immutable. The reference returned by the
getSomeList() can not be used to add something to the list. You can only get the elements of the list. The elements are immutable, therefore the whole list is immutable via this reference.
The only error could be, that I can not use the bounded wildcard
<? extends ImmutableClass>, because
ImmutableClass must be declared final to ensure immutability, so it can not be extended.
Is that bounded wildcard possible?