Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Using generics to make immutable references on mutable values

843793Jul 10 2004 — edited Feb 1 2005

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?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 1 2005
Added on Jul 10 2004
15 comments
656 views