Skip to content
Related Articles

Related Articles

How to Make a Collection Read-Only in Java?
  • Last Updated : 20 Nov, 2020
GeeksforGeeks - Summer Carnival Banner

The Collections class is used as a data structure to manage the data. We can add, remove, fetch, and update the data in the List, Set, or Map Object. Collections class has default methods for these operations. We can use those methods easily. By default, when we create an object of the Collections class, it will be Both Readable and Writable.

Read-only Collection: To make the object of Collections to Read-Only, we need to restrict an object to add, remove, or update data from it. The only operation is to fetch the data.

Java has different methods for different Collection type like unmodifiableCollection(), unmodifiableMap(), ununmodifiableSet() e.t.c. All the methods are predefined in java.util.Collecitons class.The unmodifiableCollection() is a generic method to make Read-Only collection. We need to make the reference of Collections class for that. If we have an object of Set Interface, we can use ununmodifiableSet() to make Read-Only.

Example 1: Below code shows how to make a List unmodifiable.

Java




// Java Program to make Collections Read-Only
  
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // List of Integer
        List<Integer> numbers = new ArrayList<>();
  
        // List have 1 to 10 numbers
        for (int i = 1; i <= 10; i++) {
            numbers.add(i);
        }
  
        // Iterate on the stream of integers and
        // print them
        numbers.stream().forEach(System.out::print);
  
        // Now we are adding one more element
        numbers.add(11);
  
        // Removing element from the list
        numbers.remove(8);
  
        // Updating List¶
        numbers.set(4, 4);
  
        System.out.println(
            "\nAfter Performing Some Operations");
  
        numbers.stream().forEach(System.out::print);
  
        System.out.println(
            "\nHence By default Collections object is Readable and Writable");
  
        // Now making Read-Only List
        // Using unmodifiableList() method.
        try {
            numbers = Collections.unmodifiableList(numbers);
  
            // This line will generate an Exception
            numbers.remove(11);
        }
        catch (UnsupportedOperationException
                   unsupportedOperationException) {
            System.out.println(
                "Exceptions is "
                + unsupportedOperationException);
        }
        finally {
            System.out.println(numbers.get(3));
            System.out.println(
                "Now list is only Read-Only");
        }
    }
}
Output



12345678910
After Performing Some Operations
123446781011
Hence By default Collections object is Readable and Writable
Exceptions is java.lang.UnsupportedOperationException
4
Now list is only Read-Only

Above is an example of how to make a list Read-Only. Before making Read-Only we can perform CRUD operations but after making Read-only list, set(), add(), and remove() methods will generate Exceptions. We can now only fetch the data from the list.

Example 2: Below code shows how to make a Set unmodifiable.

Java




// Java Program to make
// Set Interface Object Read-Only
  
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
  
class GFG {
  
    public static void main(String[] args)
    {
        // Set of Integer
        Set<Integer> numbers = new HashSet<Integer>();
  
        // Set have 1 to 10 numbers
        for (int i = 1; i <= 5; i++) {
            numbers.add(i);
        }
  
        // print the integers
        numbers.stream().forEach(System.out::print);
  
        // Removing element from the list
        numbers.remove(5);
  
        System.out.println("\nAfter Performing Operation");
  
        numbers.stream().forEach(System.out::print);
  
        System.out.println(
            "\nSet is also By Default Readable and Writable");
  
        // Now making Read-Only Set
        // Using unmodifiableSet() method.
        try {
            numbers = Collections.unmodifiableSet(numbers);
  
            // This line will generate an Exception
            numbers.remove(4);
        }
        catch (UnsupportedOperationException
                   unsupportedOperationException) {
            System.out.println(
                "Exceptions is "
                + unsupportedOperationException);
        }
        finally {
            System.out.println(numbers.contains(3));
            System.out.println("Now Set is Read-Only");
        }
    }
}
Output
12345
After Performing Operation
1234
Set is also By Default Readable and Writable
Exceptions is java.lang.UnsupportedOperationException
true
Now Set is Read-Only

In Above Example, We make Set as Read-Only. We can make Collections object Read-Only by using unmodifiableCollection() and to make Map Read-Only we can use unmodifiableMap() method.

MethodDescription
static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)This method accepts any of the collection objects and returns an unmodifiable view of the specified collection.
static <T> List<T> unmodifiableList(List<? extends T> list)This method accepts an object of the List interface and returns an unmodifiable view of it.
static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)This method accepts an object of the Map interface and returns an unmodifiable view of it.
static <T> Set<T> unmodifiableSet(Set<? extends T> s)This method accepts an object of the Set interface and returns an unmodifiable view of it..
static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K,? extends V> m)This method accepts an object of the SortedMap interface and returns an unmodifiable view of it.
static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)This method accepts an object of the SortedSet interface and returns an unmodifiable view of the specified sorted set.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :