ArrayList - making list unmodifiable using Collections.unmodifiableList







ArrayList - making list unmodifiable using Collections.unmodifiableList







import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
*/
public class ArrayListTest {
   public static void main(String args[]) {
          // creates array with initial capacity of 10.
          List<String> arrayList = new ArrayList<String>();
          arrayList.add("ankit");
          arrayList.add("javaMadeSoEasy");
          // getting unmodifiable list
          List<String> unmodifiableList = Collections.unmodifiableList(arrayList);
         
          /*
          * Now any attempt to modify list will throw java.lang.UnsupportedOperationException
          */
          unmodifiableList.add("mittal");
   }
}
/*OUTPUT
Exception in thread "main" java.lang.UnsupportedOperationException
   at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
   at arrayListUnModifiable.ArrayListTest.main(ArrayListTest.java:24)
*/


RELATED LINKS>

ArrayList - add, add element at specific index methods program


ArrayList - iterate using iterator, listIterator, Enumeration and enhanced for loop


ArrayList - fail-safe or fail-fast iteration using iterator, listIterator, Enumeration and enhanced for loop


ArrayList - synchronizing using Collections.synchronizedList


Vector - add, add element at specific index methods program


eEdit
Must read for you :