LinkedList - making list unmodifiable using Collections.unmodifiableList in java







LinkedList - making list unmodifiable using Collections.unmodifiableList




import java.util.LinkedList;
import java.util.Collections;
import java.util.List;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class LinkedListUnModifiableExample {
   public static void main(String args[]) {
          List<String> linkedList = new LinkedList<String>();
          linkedList.add("ankit");
          linkedList.add("javaMadeSoEasy");
          // getting unmodifiable list
          List<String> unmodifiableList = Collections.unmodifiableList(linkedList);
         
          /*
          * 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 LinkedListUnModifiableExample .main(LinkedListTest.java:23)
*/


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


No comments:

Post a Comment