Sunday, 9 August 2015

read only collections

<T> Collection<T> java.util.Collections.unmodifiableCollection(Collection<? extends T> c)

Returns an unmodifiable view of the specified collection.

This method allows modules to provide users with "read-only" access to internal collections.

Query operations on the returned collection "read through" to the specified collection. If we will try to modify the returned collection whether direct or via its iterator, result in an UnsupportedOperationException.

The returned collection will be serializable if the specified collection is serializable.

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

 * Collection read only by using
 * Collections.unmodifiableCollection()
public class ReadOnlyCollection {
     public static void main(String args[]) {

          //making existing ArrayList readonly in Java
          List<String> readableList = new ArrayList<String>();
          readableList.add("element 1");
          readableList.add("element 2");

          //creating read only Collection in Java
          Collection<String> readOnlyCollection =

          Iterator<String> itr = readOnlyCollection.iterator();
          while(itr.hasNext()) {
          //add will throw Exception because List is read only
          readOnlyCollection.add("element 3");

element 1
element 2
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source) at core.readonly.collections.ReadOnlyCollection.main(

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...