How to Create an Unmodifiable Collection in Java 9?

How to Create an Unmodifiable Collection in Java 9?

Java 9 introduced several new features, among which the unmodifiable collections have become quite popular. Unmodifiable collections provide a simple way to ensure the integrity of data by making collections immutable. This guide will walk you through the process of creating unmodifiable collections in Java 9, exploring the different types of unmodifiable collections, and showing you practical examples.

What is an Unmodifiable Collection?

An unmodifiable collection is a collection whose elements cannot be modified after its creation. The main purpose of such collections is to protect the underlying data from being altered unintentionally. For example, you might have a list of configuration settings or some constants that should not be modified during the execution of the program. Java provides built-in support for creating these collections in a simple way with the introduction of unmodifiable collections in Java 9.

Key Benefits of Unmodifiable Collections

  • Prevents data integrity issues by making collections immutable.
  • Improves security by ensuring that important collections cannot be changed after their initialization.
  • Helps in functional programming and reduces side-effects in your programs.

How to Create an Unmodifiable Collection in Java 9?

Java 9 introduced the List, Set, and Map interface methods that provide unmodifiable collections. These methods return a collection whose content cannot be modified after creation.

Unmodifiable List Example

            
import java.util.List;
import java.util.Arrays;

public class UnmodifiableListExample {
    public static void main(String[] args) {
        // Create an unmodifiable list using List.of() method in Java 9
        List fruits = List.of("Apple", "Banana", "Mango", "Orange");

        // Attempting to modify the list will throw UnsupportedOperationException
        // fruits.add("Grapes"); // Uncommenting this line will throw an exception

        System.out.println(fruits);
    }
}
            
        

In this example, we created an unmodifiable list using the List.of() method. Any attempt to modify this list (such as adding or removing elements) will throw an UnsupportedOperationException.

Unmodifiable Set Example

            
import java.util.Set;
import java.util.HashSet;

public class UnmodifiableSetExample {
    public static void main(String[] args) {
        // Create an unmodifiable set using Set.of() method in Java 9
        Set numbers = Set.of(1, 2, 3, 4, 5);

        // Attempting to modify the set will throw UnsupportedOperationException
        // numbers.add(6); // Uncommenting this line will throw an exception

        System.out.println(numbers);
    }
}
            
        

Similar to the list, we can use the Set.of() method to create an unmodifiable set. Any attempt to modify the set will lead to an exception being thrown.

Unmodifiable Map Example

            
import java.util.Map;

public class UnmodifiableMapExample {
    public static void main(String[] args) {
        // Create an unmodifiable map using Map.of() method in Java 9
        Map scores = Map.of(
            "Alice", 90,
            "Bob", 80,
            "Charlie", 85
        );

        // Attempting to modify the map will throw UnsupportedOperationException
        // scores.put("David", 95); // Uncommenting this line will throw an exception

        System.out.println(scores);
    }
}
            
        

The Map.of() method works similarly to the other methods mentioned earlier. It allows you to create an unmodifiable map. Trying to put new entries into the map will result in an exception.

How Do These Methods Differ from Older Versions of Java?

Before Java 9, developers had to rely on the Collections.unmodifiableList(), Collections.unmodifiableSet(), and Collections.unmodifiableMap() methods to create unmodifiable collections. However, the Java 9 methods are more concise and easy to use. The following is an example of how you would use the old method:

            
import java.util.Collections;
import java.util.List;
import java.util.Arrays;

public class OldUnmodifiableListExample {
    public static void main(String[] args) {
        // Using Collections.unmodifiableList() method in older versions of Java
        List fruits = Collections.unmodifiableList(Arrays.asList("Apple", "Banana", "Mango"));

        // Attempting to modify the list will throw UnsupportedOperationException
        // fruits.add("Grapes"); // Uncommenting this line will throw an exception

        System.out.println(fruits);
    }
}
            
        

The main difference is that the new methods introduced in Java 9 are much more elegant and convenient, eliminating the need for the Collections.unmodifiable* methods.

Limitations of Unmodifiable Collections

While unmodifiable collections in Java 9 prevent direct modification of the collection itself, they do not make the contents immutable. If the collection contains mutable objects, their internal state can still be modified. For example, consider the following:

            
import java.util.List;

public class UnmodifiableListWithMutableObjects {
    public static void main(String[] args) {
        // Create a mutable object inside an unmodifiable list
        List strings = List.of(
            new StringBuilder("Hello"),
            new StringBuilder("World")
        );

        // Even though the list is unmodifiable, we can still modify the internal objects
        strings.get(0).append(" Java");

        System.out.println(strings);
    }
}
            
        

In this example, we cannot modify the list itself, but we can modify the StringBuilder objects inside the list. To prevent such modifications, you need to ensure that the objects themselves are also immutable.

Conclusion

Unmodifiable collections in Java 9 are a powerful feature that simplifies the creation of immutable data structures. By using methods like List.of(), Set.of(), and Map.of(), Java developers can easily create collections that cannot be modified, providing better data integrity and code clarity.

However, it’s essential to keep in mind that making a collection unmodifiable does not make its elements immutable. If the collection holds mutable objects, their state can still be changed.

Please follow and like us:

Leave a Comment