Create Immutable ArrayList with Collections.unmodifiableList() Exmaple

In this example, we will see how to create an immutable ArrayList using Collections.unmodifiableList() method with an example.

Create Immutable ArrayList with Collections.unmodifiableList() Exmaple

public class ImmutableListExample {

    public static void main(String[] args) {

        // Creating an ArrayList of String using
        List < String > fruits = new ArrayList < > ();
        // Adding new elements to the ArrayList
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("mango");
        fruits.add("orange");

        fruits = Collections.unmodifiableList(fruits);

        // Creating Immutable List
        //fruits.add("Strawberry"); // Exception in thread "main"
        // java.lang.UnsupportedOperationException<String> fruits = List.of("Banana", "Apple", "Mango", "Orange");
        fruits.forEach(e - > System.out.println(e));
    }
}
Output:
Banana
Apple
mango
orange

References

Java ArrayList Source Code Examples


Comments