Java Collections unmodifiableSequencedCollection() Method

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

Table of Contents

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

Introduction

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

unmodifiableSequencedCollection() Method Syntax

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

public static <T> SequencedCollection<T> unmodifiableSequencedCollection(SequencedCollection<? extends T> c)

Parameters:

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

Returns:

  • An unmodifiable view of the specified SequencedCollection.

Throws:

  • NullPointerException if the specified sequenced collection is null.

Examples

Basic Usage of unmodifiableSequencedCollection()

The following example demonstrates how to use the unmodifiableSequencedCollection() method to create a read-only view of a sequenced collection.

Example

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

public class UnmodifiableSequencedCollectionExample {
    public static void main(String[] args) {
        // Create a sequenced collection with initial elements
        SequencedCollection<String> sequencedCollection = new ArrayList<>();
        sequencedCollection.add("Apple");
        sequencedCollection.add("Banana");
        sequencedCollection.add("Cherry");

        // Create an unmodifiable view of the sequenced collection
        SequencedCollection<String> unmodifiableSequencedCollection = Collections.unmodifiableSequencedCollection(sequencedCollection);

        // Display the unmodifiable sequenced collection
        System.out.println("Unmodifiable Sequenced Collection: " + unmodifiableSequencedCollection);

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

        // Display the original sequenced collection after attempted modification
        System.out.println("Original Sequenced Collection: " + sequencedCollection);
    }
}

Output:

Unmodifiable Sequenced Collection: [Apple, Banana, Cherry]
Error: Cannot modify an unmodifiable sequenced collection
Original Sequenced Collection: [Apple, Banana, Cherry]

Using unmodifiableSequencedCollection() with Custom Classes

You can also use the unmodifiableSequencedCollection() method with collections containing instances of custom classes.

Example

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

class Student {
    String name;

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

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Student student = (Student) obj;
        return name.equals(student.name);
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }
}

public class CustomUnmodifiableSequencedCollectionExample {
    public static void main(String[] args) {
        // Create a sequenced collection of students
        SequencedCollection<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 sequenced collection
        SequencedCollection<Student> unmodifiableStudents = Collections.unmodifiableSequencedCollection(students);

        // Display the unmodifiable student sequenced collection
        System.out.println("Unmodifiable Student Sequenced Collection: " + unmodifiableStudents);

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

        // Display the original student sequenced collection after attempted modification
        System.out.println("Original Student Sequenced Collection: " + students);
    }
}

Output:

Unmodifiable Student Sequenced Collection: [Amit, Neha, Raj]
Error: Cannot modify an unmodifiable student sequenced collection
Original Student Sequenced Collection: [Amit, Neha, Raj]

Explanation:

  1. Unmodifiable View: The unmodifiableSequencedCollection() method returns a read-only view of the specified sequenced collection, ensuring that any attempts to modify the collection 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 sequenced collection.

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

Real-World Use Case

Providing Read-Only Access to a Sequenced Collection

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

Example

Imagine a scenario where you have a class that manages a sequenced collection of configuration options, and you want to provide read-only access to the options.

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

class Configuration {
    private final SequencedCollection<String> options;

    public Configuration() {
        options = new ArrayList<>();
        options.add("timeout=30s");
        options.add("maxConnections=100");
        options.add("enableLogging=true");
    }

    // Method to get an unmodifiable view of the configuration options
    public SequencedCollection<String> getOptions() {
        return Collections.unmodifiableSequencedCollection(options);
    }
}

public class ConfigurationExample {
    public static void main(String[] args) {
        Configuration config = new Configuration();

        // Get the unmodifiable view of configuration options
        SequencedCollection<String> options = config.getOptions();

        // Display the configuration options
        System.out.println("Configuration Options: " + options);

        // Attempt to modify the configuration options (will throw UnsupportedOperationException)
        try {
            options.add("newOption=value");
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify configuration options");
        }
    }
}

Output:

Configuration Options: [timeout=30s, maxConnections=100, enableLogging=true]
Error: Cannot modify configuration options

Explanation:

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

  2. Immutable Collection: The example demonstrates the use of an unmodifiable sequenced collection to protect the integrity of configuration options.

Conclusion

The Collections.unmodifiableSequencedCollection() method is a powerful utility for creating unmodifiable (read-only) views of sequenced collections 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 sequenced collections 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