How to make a collection read only in java?

JavaObject Oriented ProgrammingProgramming

The Collections class of java.util package methods that exclusively work on collections these methods provide various additional operations which involves polymorphic algorithms.

This class provides different variants of the unmodifiable() method as shown below −

Sr.NoMethods & Description
1static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
This method accept any of the collection object and returns an unmodifiable view of the specified collection.
2static <T> List<T> unmodifiableList(List<? extends T> list)
This method accepts an object of the List interface and returns an unmodifiable view of it.
3static <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.
4static <T> Set<T> unmodifiableSet(Set<? extends T> s)
This method accepts an object of the Set interface and returns an unmodifiable view of it..
5static <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.
6static <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.

You can make a collection object read-only by using one of the method with respect to the collection.

Example

Following Java program creates an ArrayList object, adds elements to it, converts it into a read-only List object.

 Live Demo

import java.util.Collection;
import java.util.Collections;
import java.util.Vector;
public class CollectionReadOnly {
   public static void main(String[] args) {
      //Instantiating an ArrayList object
      Vector<String> vector = new Vector<String>();
      vector.add("JavaFx");
      vector.add("Java");
      vector.add("WebGL");
      vector.add("OpenCV");
      System.out.println(vector);
      Collection<String> immutableVector = Collections.unmodifiableCollection(vector);
      System.out.println("Vector converted to read only "+immutableVector);
      immutableVector.add("CoffeeScript");
   }
}

Exception

[JavaFx, Java, WebGL, OpenCV]
Array list converted to read only [JavaFx, Java, WebGL, OpenCV]
Exception in thread "main" java.lang.UnsupportedOperationException
   at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
   at September19.CollectionReadOnly.main(CollectionReadOnly.java:20)

Once you have retrieved the read-only view of a List object you cannot modify its contents, i.e. you cannot add or delete elements from it directly or using the Iterator object, if you do so an UnsupportedOperationException will be raised.

raja
Published on 15-Oct-2019 10:33:56
Advertisements