Saturday 28 July 2012

Making a Collection Read-Only in Java



This java example shows how to make a read-only collection using unmodifiableList, unmodifiableSet and unmodifiableMap  methods of Collections class.


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MakingCollectionReadOnly {

 public static void main(String[] argv) throws Exception {

  List numberList = new ArrayList();

  numberList.add(1);
  numberList.add(2);
  numberList.add(3);

  /**
   * Returns an unmodifiable view of the specified list. This method
   * allows modules to provide users with "read-only" access to internal
   * lists. Query operations on the returned list "read through" to the
   * specified list, and attempts to modify the returned list, whether
   * direct or via its iterator, result in an
   * UnsupportedOperationException.
   **/

  numberList = Collections.unmodifiableList(numberList);

  try {
   // Attempting to modify the read-only list, throws
   // UnsupportedOperationException

   numberList.set(0, "new value");
  } catch (UnsupportedOperationException e) {
   System.out.println("Can't modify read-only list:"+e);
  }

  Set set = new HashSet();
  set = Collections.unmodifiableSet(set);

  Map map = new HashMap();
  map = Collections.unmodifiableMap(map);
 }
}


The output is:

Can't modify read-only list:java.lang.UnsupportedOperationException


No comments:

Post a Comment