Analyze a simple code
package containers;//: containers/Unsupported.java// Unsupported operations in Java containers.import java.util.*;public class Unsupported { static void test(String msg, List<String> list) { System.out.println("--- " + msg + " ---"); Collection<String> c = list; Collection<String> subList = list.subList(1,8); // Copy of the sublist: Collection<String> c2 = new ArrayList<String>(subList); try { c.retainAll(c2); } catch(Exception e) { System.out.println("retainAll(): " + e); } try { c.removeAll(c2); } catch(Exception e) { System.out.println("removeAll(): " + e); } try { c.clear(); } catch(Exception e) { System.out.println("clear(): " + e); } try { c.add("X"); } catch(Exception e) { System.out.println("add(): " + e); } try { c.addAll(c2); } catch(Exception e) { System.out.println("addAll(): " + e); } try { c.remove("C"); } catch(Exception e) { System.out.println("remove(): " + e); } } public static void main(String[] args) { List<String> list = Arrays.asList("A B C D E F G H I J K L".split(" ")); test("Modifiable Copy", new ArrayList<String>(list)); test("Arrays.asList()", list); }} /* Output:--- Modifiable Copy ------ Arrays.asList() ---retainAll(): java.lang.UnsupportedOperationExceptionremoveAll(): java.lang.UnsupportedOperationExceptionclear(): java.lang.UnsupportedOperationExceptionadd(): java.lang.UnsupportedOperationExceptionaddAll(): java.lang.UnsupportedOperationExceptionremove(): java.lang.UnsupportedOperationException*///:~
In the main method, test ("modifiable copy", new arraylist <string> (list); this line of code is executed without any problems.
Test ("arrays. aslist ()", list); after the code is executed, a bunch of exceptions are thrown "Java. Lang. unsupportedoperationexception ".
Analysis result:
List <string> List = arrays. aslist ("a B c d e f g h I j k l". Split (""));
This line of code uses arrays. aslist to generate an array of stirng []. The length of the array is fixed. operations such as adding, deleting, and other operations on the array are not allowed.
This line of code test ("modifiable copy", new arraylist <string> (list); encapsulates the generated Array Using the arraylist container, the arraylist class of the source code to be queried inherits javasactlist and implements the list interface. You can add, delete, and perform other operations.
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable
View the abstractlist source code and you will find that if you inherit the abstractlist method but do not override the add method, an unsupportedoperationexception will be thrown.
public abstract class AbstractList extends AbstractCollection implements List { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected AbstractList() { } public void add(int index, Object element) {throw new UnsupportedOperationException(); }