user3006216
user3006216

Reputation: 43

Unmodifiable lists in java

I'm confused at what would actually happen if I tried to modify a list in java which was set to be unmodifiable, I'm relatively new to Java and from what I can find where other people have asked a similar question it is that it is still modifiable, if so why is this?

Thank you.

Upvotes: 0

Views: 83

Answers (3)

kmera
kmera

Reputation: 1745

Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.

Have a look at the documentation

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533530

You cannot set a List to be immutable. Either it is mutable or it is not. You can wrap a list with a wrapper which is immutable, however if you still have access to the underlying list you can modify it.

Upvotes: 2

Boris the Spider
Boris the Spider

Reputation: 61158

Directly from the JavaDoc:

Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.

So it will throw an UnsupportedOperationException.

Or from the source code:

    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }
    //etc...

Upvotes: 3

Related Questions