分析一個簡單的代碼
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*///:~
在main方法中test("Modifiable Copy", new ArrayList<String>(list));這行代碼執行沒有任何問題。
test("Arrays.asList()", list);代碼在執行後,拋出了一堆的異常"java.lang.UnsupportedOperationException”。
分析結果:
List<String> list = Arrays.asList("A B C D E F G H I J K L".split(" "));
這行代碼通過Arrays.asList產生Stirng[]數組,數組固定的長度,不允許對數組進行增加、刪除、等操作。
這行代碼test("Modifiable Copy", new ArrayList<String>(list));,將產生的數組,採用ArrayList容器進行封裝,經查詢源碼ArrayList類繼承AbstractList並實現List介面,並可以進行增加、刪除、等操作。
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable
查看AbstractList源碼會發現,如果單單繼承AbstractList但未重寫add方法,則會拋出UnsupportedOperationException異常。
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(); }