How to Make a Collection Read-Only in Java?
Last Updated : 11 Aug, 2021
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.Collections 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"); } } }
Output12345678910 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"); } } }
Output12345 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.
Similar Reads
How to make an ArrayList read only in Java Given an ArrayList, the task is to make this ArrayList read-only in Java. Examples: Input: ArrayList: [1, 2, 3, 4, 5] Output: Read-only ArrayList: [1, 2, 3, 4, 5] Input: ArrayList: [geeks, for, geeks] Output: Read-only ArrayList: [geeks, for, geeks] An ArrayList can be made read-only easily with the
2 min read
Collection add() Method in Java with Examples The add(E element) of java.util.Collection interface is used to add the element 'element' to this collection. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false. Syntax: Collection.add(E element) Paramet
4 min read
Need of Concurrent Collections in java In Java, multiple threads can work at the same time, but when the applications become complex, it is very important to handle multiple threads at the same time. With the help of concurrency, different tasks can run in parallel, which can improve the performance of the application. Managing shared da
3 min read
How to Learn Java Collections - A Complete Guide In the real world, a collection by definition is a group of articles that have similar properties and attributes. Since Java is an Object-Oriented Language it mimics the real world. In Java, a Collection is a group of multiple objects put together into a single unit. Java Collections is a very vast
15+ min read
Collection addAll() method in Java with Examples The addAll(Collection collection) of java.util.Collection interface is used to add the Collection 'collection' to this existing collection. This method returns a boolean value depicting the successfulness of the operation. If the collection was added, it returns true, else it returns false. Syntax:
3 min read