Sobes.tech
Junior

How to obtain a collection that is only accessible for reading?

sobes.tech AI

Answer from AI

Use static methods like Collections.unmodifiable*() such as Collections.unmodifiableList(), Collections.unmodifiableSet(), Collections.unmodifiableMap(), or Collections.unmodifiableCollection(). These methods return a wrapper around the original collection that throws UnsupportedOperationException when modification is attempted.

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

public class UnmodifiableCollectionExample {

    public static void main(String[] args) {
        List<String> mutableList = new ArrayList<>();
        mutableList.add("Element 1");
        mutableList.add("Element 2");

        // Getting an unmodifiable collection
        List<String> unmodifiableList = Collections.unmodifiableList(mutableList);

        System.out.println("Unmodifiable list: " + unmodifiableList);

        // Attempting to modify will throw an exception
        try {
            unmodifiableList.add("New element");
        } catch (UnsupportedOperationException e) {
            System.out.println("Attempt to add an element to an unmodifiable list caused an exception: " + e);
        }
    }
}

Note that an unmodifiable collection is only for read access over an existing collection. If the original collection is changed, these changes will be visible through the unmodifiable wrapper. To create a completely independent unmodifiable copy, first copy the elements into a new collection, then wrap it.

You can also use factory methods from List.of(), Set.of(), Map.of() (since Java 9) to create unmodifiable collections with a predefined set of elements.

import java.util.List;
import java.util.Set;
import java.util.Map;

public class ImmutableFactoryExample {

    public static void main(String[] args) {
        List<String> immutableList = List.of("A", "B", "C");
        Set<Integer> immutableSet = Set.of(1, 2, 3);
        Map<String, Integer> immutableMap = Map.of("one", 1, "two", 2);

        System.out.println("Unmodifiable list: " + immutableList);
        System.out.println("Unmodifiable set: " + immutableSet);
        System.out.println("Unmodifiable map: " + immutableMap);

        // Attempting to modify
        try {
            immutableList.add("D");
        } catch (UnsupportedOperationException e) {
            System.out.println("Attempt to add an element to an unmodifiable list (factory method) caused an exception: " + e);
        }
    }
}