Sobes.tech
Junior — Middle

How can you obtain an unmodifiable list based on an existing ArrayList?

sobes.tech AI

Answer from AI

To obtain an immutable list based on an existing ArrayList in Java, you can use the Collections.unmodifiableList() method. This method returns a wrapper around the original list that does not allow modifications through the obtained interface.

Example:

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

ArrayList<String> mutableList = new ArrayList<>();
mutableList.add("Element 1");
mutableList.add("Element 2");

List<String> immutableList = Collections.unmodifiableList(mutableList);

// Attempting to modify immutableList will throw UnsupportedOperationException
// immutableList.add("New Element"); // Error!

It is important to remember that if the original mutableList changes, the changes will also be visible in immutableList, as it is only a wrapper. If full immutability is needed, create a copy of the list and wrap it:

List<String> trulyImmutableList = Collections.unmodifiableList(new ArrayList<>(mutableList));
How can you obtain an unmodifiable list based on an… - sobes.tech