Unmodifiable Collection

suggest change

Sometimes it’s not a good practice to expose an internal collection since it can lead to a malicious code vulnerability due to its mutable characteristic. In order to provide “read-only” collections, Java provides its unmodifiable versions.

An unmodifiable collection is often a view of a modifiable collection, which guarantees that the collection itself cannot be altered through that view. Attempts to modify it will result in an UnsupportedOperationException.

It is important to notice that objects which are present inside the collection can still be altered.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyPojoClass {
    private List<Integer> intList = new ArrayList<>();

    public void addValueToIntList(Integer value){
        intList.add(value);
    }
    
    public List<Integer> getIntList() {
        return Collections.unmodifiableList(intList);
    }
}

The following attempt to modify an unmodifiable collection will throw an exception:

import java.util.Collections;
import java.util.List;

public class App {

    private static final class MyPojoClass {
        private final List<Integer> intList = new java.util.ArrayList<>();

        void addValueToIntList(Integer value) {
            intList.add(value);
        }

        List<Integer> getIntList() {
            return Collections.unmodifiableList(intList);
        }
    }

    public static void main(String[] args) {
        MyPojoClass pojo = new MyPojoClass();
        pojo.addValueToIntList(42);
        
        List<Integer> list = pojo.getIntList();
        list.add(69);
    }
}
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
    at App.main(App.java:12)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents