Friday, September 7, 2012

How to create read only Collection in Java


 


SUNDAY, September 8, 2012


How to create read only Collection in Java

Read only Collection in Java
You can create read only Collection by using Collections.unmodifiableCollection() utiltiy method. it returns unmodifiable or readonly 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 over iterator. It raise 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 usingArrays.asList(String{[]), which is apparently not true as this method only return a fixed size list on which add() andremove() are not allowed by set() method is still allowed which can change the contents of ArrayListCollections class also provide 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.

READ ONLY COLLECTION EXAMPLE - 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.

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
 */

public class ReadOnlyCollection {


    public static void main(String args[]) {
   
        //creating read only Collection in Java
        Collection readOnlyCollection = Collections.unmodifiableCollection(newArrayList<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 than you will get 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 all the lines which does modification on read only list than 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 value of existing element using set method.

No comments:

Post a Comment