How to Make Collection like ArrayList Read Only in Java?

Read only Collection in Java
You can create read-only Collection by using Collections.unmodifiableCollection() utility method. it returns a 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 misconception 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 on which add() and remove() are not allowed by set() method is still allowed which can change the contents of ArrayList. Collections class also provide 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 fixed size List as well.

Making ArrayList Read Only - Java

How to make Collection Read only in Java examplehere is 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 creation on same line and than later wrapped it into 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
        //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

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

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

If you comment all the lines which do modification on 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 allow to update the value of an existing element using the set method.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures and Algorithms: Deep Dive Using Java

If you like this tutorial and want to learn more about Java Collection Framework, don't forget to checkout 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 element 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 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 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 difference between TreeMap and TreeSet in Java? (answer)
  • What is difference between ArrayList and HashSet in Java? (answer)

No comments:

Post a Comment