Java Collections unmodifiableList() Method

The unmodifiableList() method in Java is a utility method provided by the java.util.Collections class. It returns an unmodifiable view of the specified list, meaning that any attempts to modify the list through this view will result in an UnsupportedOperationException. This method is useful when you need to provide a read-only view of a list, ensuring that the original list remains unchanged.

Table of Contents

  1. Introduction
  2. unmodifiableList() Method Syntax
  3. Examples
    • Basic Usage of unmodifiableList()
    • Using unmodifiableList() with Custom Classes
  4. Real-World Use Case
  5. Conclusion

Introduction

The Collections.unmodifiableList() method allows you to create a read-only view of an existing list. The returned list does not allow any modifications such as adding, removing, or updating elements. This is useful in scenarios where you want to share a list with other parts of your program without allowing them to alter it, ensuring data integrity and immutability.

unmodifiableList() Method Syntax

The syntax for the unmodifiableList() method is as follows:

public static <T> List<T> unmodifiableList(List<? extends T> list)

Parameters:

  • list: The list for which an unmodifiable view is to be returned.

Returns:

  • An unmodifiable view of the specified list.

Throws:

  • NullPointerException if the specified list is null.

Examples

Basic Usage of unmodifiableList()

The following example demonstrates how to use the unmodifiableList() method to create a read-only view of a list.

Example

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

public class UnmodifiableListExample {
    public static void main(String[] args) {
        // Create a list with initial elements
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        // Create an unmodifiable view of the list
        List<String> unmodifiableList = Collections.unmodifiableList(list);

        // Display the unmodifiable list
        System.out.println("Unmodifiable List: " + unmodifiableList);

        // Attempt to modify the unmodifiable list (will throw UnsupportedOperationException)
        try {
            unmodifiableList.add("Date");
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an unmodifiable list");
        }

        // Display the original list after attempted modification
        System.out.println("Original List: " + list);
    }
}

Output:

Unmodifiable List: [Apple, Banana, Cherry]
Error: Cannot modify an unmodifiable list
Original List: [Apple, Banana, Cherry]

Using unmodifiableList() with Custom Classes

You can also use the unmodifiableList() method with lists containing instances of custom classes.

Example

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

class Student {
    String name;

    Student(String name) {
        this.name = name;
    }

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

public class CustomUnmodifiableListExample {
    public static void main(String[] args) {
        // Create a list of students
        List<Student> students = new ArrayList<>();
        students.add(new Student("Amit"));
        students.add(new Student("Neha"));
        students.add(new Student("Raj"));

        // Create an unmodifiable view of the student list
        List<Student> unmodifiableStudents = Collections.unmodifiableList(students);

        // Display the unmodifiable student list
        System.out.println("Unmodifiable Student List: " + unmodifiableStudents);

        // Attempt to modify the unmodifiable student list (will throw UnsupportedOperationException)
        try {
            unmodifiableStudents.add(new Student("Vikram"));
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an unmodifiable student list");
        }

        // Display the original student list after attempted modification
        System.out.println("Original Student List: " + students);
    }
}

Output:

Unmodifiable Student List: [Amit, Neha, Raj]
Error: Cannot modify an unmodifiable student list
Original Student List: [Amit, Neha, Raj]

Explanation:

  1. Unmodifiable View: The unmodifiableList() method returns a read-only view of the specified list, ensuring that any attempts to modify the list through this view will result in an UnsupportedOperationException.

  2. Immutable Nature: The example shows that any modification attempts result in an exception, demonstrating the immutability of the unmodifiable list.

  3. Custom Class: The method works with custom class instances, allowing you to create unmodifiable views of lists containing user-defined objects.

Real-World Use Case

Providing Read-Only Access to a List

In real-world applications, the unmodifiableList() method can be used to provide read-only access to a list, such as when returning a list from a method that should not be modified by the caller.

Example

Imagine a scenario where you have a class that manages a list of products, and you want to provide read-only access to the list of products.

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

class Product {
    String name;

    Product(String name) {
        this.name = name;
    }

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

class ProductManager {
    private final List<Product> products;

    public ProductManager() {
        products = new ArrayList<>();
        products.add(new Product("Laptop"));
        products.add(new Product("Smartphone"));
        products.add(new Product("Tablet"));
    }

    // Method to get an unmodifiable view of the product list
    public List<Product> getProducts() {
        return Collections.unmodifiableList(products);
    }
}

public class ProductExample {
    public static void main(String[] args) {
        ProductManager productManager = new ProductManager();

        // Get the unmodifiable view of the product list
        List<Product> products = productManager.getProducts();

        // Display the product list
        System.out.println("Product List: " + products);

        // Attempt to modify the product list (will throw UnsupportedOperationException)
        try {
            products.add(new Product("Monitor"));
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify the product list");
        }
    }
}

Output:

Product List: [Laptop, Smartphone, Tablet]
Error: Cannot modify the product list

Explanation:

  1. Read-Only Access: The getProducts() method returns an unmodifiable view of the product list, ensuring that the list cannot be modified externally.

  2. Immutable List: The example demonstrates the use of an unmodifiable list to protect the integrity of product data.

Conclusion

The Collections.unmodifiableList() method is a powerful utility for creating unmodifiable (read-only) views of lists in Java. By providing a simple way to ensure immutability, it enhances the flexibility and safety of your code by preventing unintended modifications. This method is particularly valuable in scenarios where you need to protect the integrity of lists while providing access to them, improving the robustness and maintainability of your Java applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top