Sunday, 9 August 2015

Read only arraylist

java.util.Collections.unmodifiableList(List<? extends T> list)

Returns an unmodifiable view of the specified list.

This method returns list "read only" list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.

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

Similarly, the returned list will implement RandomAccess if the specified list does.

package core.readonly.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Java program to create read only List in Java.
 * List read only by using Collections.unmodifiableList().
 */
public class ReadOnlyList {

       public static void main(String args[]) {
             
             ArrayList<String> readableList = new ArrayList<String>();
             readableList.add("element 1");
             readableList.add("element 2");
             
             //making existing ArrayList read only in Java
             List<String> unmodifiableList =
                         Collections.unmodifiableList(readableList);
             
             for(String elements : unmodifiableList) {
                    System.out.println(elements);    
             }

             //add will throw Exception because List is read only
             unmodifiableList.add("element 3");

             //remove is not allowed in unmodifiable list
             unmodifiableList.remove(0);

       }
}

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

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...