简体   繁体   中英

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.

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...

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM