Java List copyOf()

Introduction

The List.copyOf() method in Java 10 allows you to create an unmodifiable copy of a list, and it can be applied to lists of different data types like integers, strings, custom objects, etc. 

The returned list is immutable, meaning any modification attempts will throw an UnsupportedOperationException. Moreover, the list cannot contain null elements; any list containing null will cause a NullPointerException.

In this guide, we will demonstrate how to use List.copyOf() with lists of various types, including integers, strings, and custom objects.

Solution Steps

  1. Create Lists of Different Types: Create lists of strings, integers, and custom objects.
  2. Use List.copyOf(): Create unmodifiable copies of these lists.
  3. Attempt Modifications: Attempt to modify the copied lists, which will result in an exception.
  4. Display the Lists: Print the original and copied lists to verify their contents.

Java Program

Example 1: Copying a List of Strings

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

public class ListCopyOfStringExample {
    public static void main(String[] args) {
        // Step 1: Create a mutable list of strings
        List<String> stringList = new ArrayList<>();
        stringList.add("Apple");
        stringList.add("Banana");
        stringList.add("Orange");

        // Step 2: Create an unmodifiable copy of the list
        List<String> unmodifiableStringList = List.copyOf(stringList);

        // Step 3: Display the unmodifiable list
        System.out.println("Unmodifiable String List: " + unmodifiableStringList);

        // Step 4: Attempt to modify the unmodifiable list (throws exception)
        try {
            unmodifiableStringList.add("Grapes");
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an unmodifiable string list");
        }
    }
}

Output

Unmodifiable String List: [Apple, Banana, Orange]
Error: Cannot modify an unmodifiable string list

Example 2: Copying a List of Integers

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

public class ListCopyOfIntegerExample {
    public static void main(String[] args) {
        // Step 1: Create a mutable list of integers
        List<Integer> intList = new ArrayList<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);

        // Step 2: Create an unmodifiable copy of the list
        List<Integer> unmodifiableIntList = List.copyOf(intList);

        // Step 3: Display the unmodifiable list
        System.out.println("Unmodifiable Integer List: " + unmodifiableIntList);

        // Step 4: Attempt to modify the unmodifiable list (throws exception)
        try {
            unmodifiableIntList.add(4);
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an unmodifiable integer list");
        }
    }
}

Output

Unmodifiable Integer List: [1, 2, 3]
Error: Cannot modify an unmodifiable integer list

Example 3: Copying a List of Custom Objects

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

public class ListCopyOfCustomObjectExample {
    public static void main(String[] args) {
        // Step 1: Create a mutable list of Employee objects
        List<Employee> employeeList = new ArrayList<>();
        employeeList.add(new Employee("Ravi", 30));
        employeeList.add(new Employee("Amit", 28));
        employeeList.add(new Employee("Pooja", 35));

        // Step 2: Create an unmodifiable copy of the list
        List<Employee> unmodifiableEmployeeList = List.copyOf(employeeList);

        // Step 3: Display the unmodifiable list
        System.out.println("Unmodifiable Employee List: " + unmodifiableEmployeeList);

        // Step 4: Attempt to modify the unmodifiable list (throws exception)
        try {
            unmodifiableEmployeeList.add(new Employee("Neha", 27));
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an unmodifiable employee list");
        }
    }
}

class Employee {
    private String name;
    private int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

Output

Unmodifiable Employee List: [Ravi (30), Amit (28), Pooja (35)]
Error: Cannot modify an unmodifiable employee list

Explanation

Example 1: Copying a List of Strings

List<String> stringList = new ArrayList<>();
stringList.add("Apple");
stringList.add("Banana");
stringList.add("Orange");
List<String> unmodifiableStringList = List.copyOf(stringList);
  • Original List: A mutable list containing strings "Apple", "Banana", and "Orange".
  • Unmodifiable List: List.copyOf() creates an immutable copy of stringList.
  • Modification Attempt: An attempt to modify unmodifiableStringList results in an UnsupportedOperationException.

Example 2: Copying a List of Integers

List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
intList.add(3);
List<Integer> unmodifiableIntList = List.copyOf(intList);
  • Original List: A mutable list containing integers 1, 2, and 3.
  • Unmodifiable List: List.copyOf() creates an immutable copy of intList.
  • Modification Attempt: An attempt to modify unmodifiableIntList throws an UnsupportedOperationException.

Example 3: Copying a List of Custom Objects

List<Employee> employeeList = new ArrayList<>();
employeeList.add(new Employee("Ravi", 30));
employeeList.add(new Employee("Amit", 28));
employeeList.add(new Employee("Pooja", 35));
List<Employee> unmodifiableEmployeeList = List.copyOf(employeeList);
  • Original List: A list of custom Employee objects.
  • Unmodifiable List: List.copyOf() creates an immutable copy of the employeeList.
  • Modification Attempt: Any attempt to modify the unmodifiable list will throw an UnsupportedOperationException.

Conclusion

The List.copyOf() method introduced in Java 10 provides a simple way to create unmodifiable copies of lists, ensuring immutability and thread safety. It works with lists containing various types, such as strings, integers, and custom objects. However, it does not allow any null values and throws exceptions when attempting to modify the list. This method is especially useful when you want to create read-only views of collections to prevent accidental modifications.

Comments