In Java, you can create an immutable List using the Collections.unmodifiableList() method. The unmodifiableList() method returns an unmodifiable view of the specified list. Any attempt to modify the returned list will result in an UnsupportedOperationException.
Here’s an example code that demonstrates how to create an immutable List:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");
list.add("Three");
List<String> immutableList = Collections.unmodifiableList(list);
// This will throw an UnsupportedOperationException
immutableList.add("Four");
}
}
In this example, we create an ArrayList and add three strings to it. We then create an immutable view of the ArrayList using the Collections.unmodifiableList() method. Finally, we try to add a string to the immutable list, which results in an UnsupportedOperationException.
Note that the elements of the underlying list can still be modified, and the modifications will be reflected in the immutable view. Therefore, you should only use unmodifiableList() to create an immutable view of a list if you’re sure that the elements of the list won’t be modified.