Java Collections unmodifiableSequencedSet() Method

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

Table of Contents

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

Introduction

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

unmodifiableSequencedSet() Method Syntax

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

public static <T> SequencedSet<T> unmodifiableSequencedSet(SequencedSet<? extends T> s)

Parameters:

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

Returns:

  • An unmodifiable view of the specified SequencedSet.

Throws:

  • NullPointerException if the specified sequenced set is null.

Examples

Basic Usage of unmodifiableSequencedSet()

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

Example

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.SequencedSet;

public class UnmodifiableSequencedSetExample {
    public static void main(String[] args) {
        // Create a sequenced set with initial elements
        SequencedSet<String> sequencedSet = new LinkedHashSet<>();
        sequencedSet.add("Apple");
        sequencedSet.add("Banana");
        sequencedSet.add("Cherry");

        // Create an unmodifiable view of the sequenced set
        SequencedSet<String> unmodifiableSequencedSet = Collections.unmodifiableSequencedSet(sequencedSet);

        // Display the unmodifiable sequenced set
        System.out.println("Unmodifiable Sequenced Set: " + unmodifiableSequencedSet);

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

        // Display the original sequenced set after attempted modification
        System.out.println("Original Sequenced Set: " + sequencedSet);
    }
}

Output:

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

Using unmodifiableSequencedSet() with Custom Classes

You can also use the unmodifiableSequencedSet() method with sets containing instances of custom classes.

Example

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.SequencedSet;

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 CustomUnmodifiableSequencedSetExample {
    public static void main(String[] args) {
        // Create a sequenced set of students
        SequencedSet<Student> students = new LinkedHashSet<>();
        students.add(new Student("Amit"));
        students.add(new Student("Neha"));
        students.add(new Student("Raj"));

        // Create an unmodifiable view of the student sequenced set
        SequencedSet<Student> unmodifiableStudents = Collections.unmodifiableSequencedSet(students);

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

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

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

Output:

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

Explanation:

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

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

Real-World Use Case

Providing Read-Only Access to a Sequenced Set

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

Example

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

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.SequencedSet;

class Configuration {
    private final SequencedSet<String> configKeys;

    public Configuration() {
        configKeys = new LinkedHashSet<>();
        configKeys.add("timeout");
        configKeys.add("maxConnections");
        configKeys.add("enableLogging");
    }

    // Method to get an unmodifiable view of the configuration keys
    public SequencedSet<String> getConfigKeys() {
        return Collections.unmodifiableSequencedSet(configKeys);
    }
}

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

        // Get the unmodifiable view of configuration keys
        SequencedSet<String> keys = config.getConfigKeys();

        // Display the configuration keys
        System.out.println("Configuration Keys: " + keys);

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

Output:

Configuration Keys: [timeout, maxConnections, enableLogging]
Error: Cannot modify configuration keys

Explanation:

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

  2. Immutable Set: The example demonstrates the use of an unmodifiable sequenced set to protect the integrity of configuration keys.

Conclusion

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