Java Collections unmodifiableSequencedMap() Method

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

Table of Contents

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

Introduction

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

unmodifiableSequencedMap() Method Syntax

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

public static <K, V> SequencedMap<K, V> unmodifiableSequencedMap(SequencedMap<? extends K, ? extends V> m)

Parameters:

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

Returns:

  • An unmodifiable view of the specified SequencedMap.

Throws:

  • NullPointerException if the specified sequenced map is null.

Examples

Basic Usage of unmodifiableSequencedMap()

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

Example

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SequencedMap;

public class UnmodifiableSequencedMapExample {
    public static void main(String[] args) {
        // Create a sequenced map with initial entries
        SequencedMap<String, String> sequencedMap = new LinkedHashMap<>();
        sequencedMap.put("Apple", "Fruit");
        sequencedMap.put("Carrot", "Vegetable");
        sequencedMap.put("Banana", "Fruit");

        // Create an unmodifiable view of the sequenced map
        SequencedMap<String, String> unmodifiableSequencedMap = Collections.unmodifiableSequencedMap(sequencedMap);

        // Display the unmodifiable sequenced map
        System.out.println("Unmodifiable Sequenced Map: " + unmodifiableSequencedMap);

        // Attempt to modify the unmodifiable sequenced map (will throw UnsupportedOperationException)
        try {
            unmodifiableSequencedMap.put("Date", "Fruit");
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an unmodifiable sequenced map");
        }

        // Display the original sequenced map after attempted modification
        System.out.println("Original Sequenced Map: " + sequencedMap);
    }
}

Output:

Unmodifiable Sequenced Map: {Apple=Fruit, Carrot=Vegetable, Banana=Fruit}
Error: Cannot modify an unmodifiable sequenced map
Original Sequenced Map: {Apple=Fruit, Carrot=Vegetable, Banana=Fruit}

Using unmodifiableSequencedMap() with Custom Classes

You can also use the unmodifiableSequencedMap() method with maps containing instances of custom classes.

Example

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SequencedMap;

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 CustomUnmodifiableSequencedMapExample {
    public static void main(String[] args) {
        // Create a sequenced map of students and their scores
        SequencedMap<Student, Integer> studentScores = new LinkedHashMap<>();
        studentScores.put(new Student("Amit"), 85);
        studentScores.put(new Student("Neha"), 90);
        studentScores.put(new Student("Raj"), 78);

        // Create an unmodifiable view of the student sequenced map
        SequencedMap<Student, Integer> unmodifiableStudentScores = Collections.unmodifiableSequencedMap(studentScores);

        // Display the unmodifiable student sequenced map
        System.out.println("Unmodifiable Student Sequenced Map: " + unmodifiableStudentScores);

        // Attempt to modify the unmodifiable student sequenced map (will throw UnsupportedOperationException)
        try {
            unmodifiableStudentScores.put(new Student("Vikram"), 88);
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an unmodifiable student sequenced map");
        }

        // Display the original student sequenced map after attempted modification
        System.out.println("Original Student Sequenced Map: " + studentScores);
    }
}

Output:

Unmodifiable Student Sequenced Map: {Amit=85, Neha=90, Raj=78}
Error: Cannot modify an unmodifiable student sequenced map
Original Student Sequenced Map: {Amit=85, Neha=90, Raj=78}

Explanation:

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

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

Real-World Use Case

Providing Read-Only Access to a Sequenced Map

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

Example

Imagine a scenario where you have a class that manages a sequenced map of product prices, and you want to provide read-only access to the prices.

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SequencedMap;

class Product {
    String name;

    Product(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;
        Product product = (Product) obj;
        return name.equals(product.name);
    }

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

class ProductManager {
    private final SequencedMap<Product, Double> productPrices;

    public ProductManager() {
        productPrices = new LinkedHashMap<>();
        productPrices.put(new Product("Laptop"), 1500.00);
        productPrices.put(new Product("Smartphone"), 800.00);
        productPrices.put(new Product("Tablet"), 300.00);
    }

    // Method to get an unmodifiable view of the product prices
    public SequencedMap<Product, Double> getProductPrices() {
        return Collections.unmodifiableSequencedMap(productPrices);
    }
}

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

        // Get the unmodifiable view of product prices
        SequencedMap<Product, Double> prices = productManager.getProductPrices();

        // Display the product prices
        System.out.println("Product Prices: " + prices);

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

Output:

Product Prices: {Laptop=1500.0, Smartphone=800.0, Tablet=300.0}
Error: Cannot modify product prices

Explanation:

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

  2. Immutable Map: The example demonstrates the use of an unmodifiable sequenced map to protect the integrity of product price data.

Conclusion

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