Saturday 18 February 2012

creating unmodifiable list

You can use an unmodifiable wrapper to create a collection that offers read-only access to
others, while allowing read/write access to yourself. You do this simply by giving others a
reference to the unmodifiable wrapper while retaining for yourself a reference to the
original collection.


1.package com.usr.collections;
2.
3.import java.util.Arrays;
4.import java.util.Collections;
5.import java.util.List;
6.
7.public class UnmodifiableList {
8.       public static void main(String[] args) {
9.
10.              String[] strArr = { "sunday", "monday", "tuesday", "wednesday",
                        "thursday", "friday", "saturday" };
11.              List<String> strList = Arrays.asList(strArr);
12.              List<String> unmodifiableList = Collections.unmodifiableList(strList);
13.              // unmodifiableList.add("sunday");
14.              for (String temp : unmodifiableList) {
15.                     System.out.println(temp);
16.              }
17.       }
18.}


In the above program if line 13 is uncommented then we get

Exception in thread "main" java.lang.UnsupportedOperationException
       at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
                                                          at com.usr.collections.UnmodifiableList.main(UnmodifiableList.java:13)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.