Thursday, September 28, 2023

How to Create Read Only and Unmodifiable ArrayList in Java? Example

Read-only Collection in Java
You can create read-only Collection by using Collections.unmodifiableCollection() utility method. it returns an unmodifiable or read-only view of Collection in which you can not perform any operation which will change the collection like add(), remove() and set() either directly or while iterating using Iterator or ListIterator. It will throw UnsupportedOperationException whenever you try to modify the List. 

One of the common misconceptions around read-only ArrayList is that you can create read-only ArrayList by using Arrays.asList(String{[]), which is apparently not true as this method only return a fixed-size list.

You cannot perform add() and remove() but the set() method is still allowed which can change the contents of ArrayList. Collections class also provides a different method to make List and Set read-only. 

In this Java tutorial, we will learn How to make any collection read only and How to create a fixed size List as well.



Making ArrayList Read-Only - Java

How to make Collection Read only in Java examplehere is a code example of creating and making existing ArrayList read-only. This example uses Arrays.asList() method to create a fixed-length ArrayList which is initialized during the creation on the same line and then later wrapped it into the unmodifiable collection to make it read only.

Java Program to create unmodifiable ArrayList

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

/**
 * Java Program to create read only Collection in Java.

 * apparently you can make any
 * Collection read only by using

 * Collections.unmodifiableCollection(), there are separate
 * method for List and Set as well.

 *
 * @author Javin Paul
 */

public class ReadOnlyCollection {
 
 
    public static void main(String args[]) {
     
        //creating read only Collection in Java
        Collection readOnlyCollection = Collections.unmodifiableCollection(new ArrayList<String>());
        readOnlyCollection.add("Sydney Sheldon"); //raises UnSupportedOperation exception
   
        //making existing ArrayList readonly in Java
        ArrayList readableList = new ArrayList();
        readableList.add("Jeffrey Archer");
        readableList.add("Khalid Hussain");
     
        List unmodifiableList = Collections.unmodifiableList(readableList);
     
        //add will throw Exception because List is readonly
        unmodifiableList.add("R.K. Narayan");
     
        //remove is not allowed in unmodifiable list
        unmodifiableList.remove(0);
     
        //set is not allowed in unmodifiable List
        unmodifiableList.set(0, "Anurag Kashyap");
     
        //creating Fixed Length List from Array in Java
        List fixedLengthList = Arrays.asList("Mark" , "Twen");
        // readOnlyList.add("J.K. Rowling"); //raises Exception
     
        fixedLengthList.set(0, "J.K. Rowling"); //allowed that's why not read only list
        System.out.println(fixedLengthList.get(0));
    }
 
}

If you un-comment lines which supposed to raise Exception then you will get an Exception like this:

Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.add(Collections.java:1018)
        at test.CollectionTest.main(CollectionTest.java:24)

If you comment on all the lines which do modification on the read-only list then you can test the last line which changes the value of an element in fixed-length ArrayList.


That’s all on How to create read-only Collection in Java. Read-only collection is also called unmodifiable collection and does not allow any modification operation like add() , remove() or set() operation. 

Remember read-only collection is different than fixed-length collection which does not allow add or remove method but allows to update the value of an existing element using the set method.

If you like this tutorial and want to learn more about Java Collection Framework, don't forget to check out these amazing tutorials from Java67 Blog :
  • When to use LinkedHashSet, TreeSet, and HashSet in Java? (answer)
  • How to use Iterator in Java? (solution)
  • How to use ArrayList in Java? (tutorial)
  • How to search elements in Java array? (solution)
  • How to traverse HashSet in Java? (answer)
  • Difference between ArrayList and Vector in Java? (answer)
  • When to use CopyOnWriteArrayList in Java? (answer)
  • Top 20 Interview Questions from Java Collection Framework (questions)
  • How to loop over ArrayList in Java? (solution)
  • Difference between HashSet and HashMap in Java? (answer)
  • What is the difference between Hashtable and HashMap in Java? (answer)
  • Difference between HashMap and ConcurrentHashMap in Java? (answer)
  • How to sort ArrayList in Java? (solution)
  • What is the difference between List and Set in Java? (answer)
  • Difference between ArrayList and HashMap in Java? (answer)
  • Difference between HashSet and TreeSet in Java? (answer)
  • What is the difference between TreeMap and TreeSet in Java? (answer)
  • What is the difference between ArrayList and HashSet in Java? (answer)
Thanks for reading this article so far. If you have any doubt or questions feel free to ask in comments. Also what was the last collection related question you were asked on Java interviews? If you remember then please share with us on comments. 

1 comment:

Feel free to comment, ask questions if you have any doubt.