Wednesday, 9 May 2018

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


Java here 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
        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 Exception like this:

Oracle Java Guides, Oracle Java Learning, Oracle Java Tutorials and Materials

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 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.

Related Posts