Java Collections unmodifiableNavigableSet() Method

The unmodifiableNavigableSet() method in Java is a utility method provided by the java.util.Collections class. It returns an unmodifiable view of the specified navigable set, 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 navigable set, ensuring that the original set remains unchanged.

Table of Contents

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

Introduction

The Collections.unmodifiableNavigableSet() method allows you to create a read-only view of an existing navigable set. 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 navigable set with other parts of your program without allowing them to alter it, ensuring data integrity and immutability.

unmodifiableNavigableSet() Method Syntax

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

public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s)

Parameters:

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

Returns:

  • An unmodifiable view of the specified navigable set.

Throws:

  • NullPointerException if the specified navigable set is null.

Examples

Basic Usage of unmodifiableNavigableSet()

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

Example

import java.util.Collections;
import java.util.NavigableSet;
import java.util.TreeSet;

public class UnmodifiableNavigableSetExample {
    public static void main(String[] args) {
        // Create a navigable set with initial elements
        NavigableSet<String> navigableSet = new TreeSet<>();
        navigableSet.add("Apple");
        navigableSet.add("Banana");
        navigableSet.add("Cherry");

        // Create an unmodifiable view of the navigable set
        NavigableSet<String> unmodifiableNavigableSet = Collections.unmodifiableNavigableSet(navigableSet);

        // Display the unmodifiable navigable set
        System.out.println("Unmodifiable Navigable Set: " + unmodifiableNavigableSet);

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

        // Display the original navigable set after attempted modification
        System.out.println("Original Navigable Set: " + navigableSet);
    }
}

Output:

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

Using unmodifiableNavigableSet() with Custom Classes

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

Example

import java.util.Collections;
import java.util.NavigableSet;
import java.util.TreeSet;

class Student implements Comparable<Student> {
    String name;
    int id;

    Student(String name, int id) {
        this.name = name;
        this.id = id;
    }

    @Override
    public int compareTo(Student other) {
        return Integer.compare(this.id, other.id);
    }

    @Override
    public String toString() {
        return name + " (ID: " + id + ")";
    }

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

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

public class CustomUnmodifiableNavigableSetExample {
    public static void main(String[] args) {
        // Create a navigable set of students
        NavigableSet<Student> students = new TreeSet<>();
        students.add(new Student("Amit", 101));
        students.add(new Student("Neha", 102));
        students.add(new Student("Raj", 103));

        // Create an unmodifiable view of the student navigable set
        NavigableSet<Student> unmodifiableStudents = Collections.unmodifiableNavigableSet(students);

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

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

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

Output:

Unmodifiable Student Navigable Set: [Amit (ID: 101), Neha (ID: 102), Raj (ID: 103)]
Error: Cannot modify an unmodifiable student navigable set
Original Student Navigable Set: [Amit (ID: 101), Neha (ID: 102), Raj (ID: 103)]

Explanation:

  1. Unmodifiable View: The unmodifiableNavigableSet() method returns a read-only view of the specified navigable 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 navigable set.

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

Real-World Use Case

Providing Read-Only Access to a Navigable Set

In real-world applications, the unmodifiableNavigableSet() method can be used to provide read-only access to a navigable 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 navigable set of configuration keys, and you want to provide read-only access to the keys.

import java.util.Collections;
import java.util.NavigableSet;
import java.util.TreeSet;

class Configuration {
    private final NavigableSet<String> configKeys;

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

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

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

        // Get the unmodifiable view of configuration keys
        NavigableSet<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: [enableLogging, maxConnections, timeout]
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 navigable set to protect the integrity of configuration keys.

Conclusion

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