天天看点

java 不支持的操作异常_Java集合(4):未获支持的操作及UnsupportedOperationException

1 importjava.util.ArrayList;2 importjava.util.Arrays;3 importjava.util.Collection;4 importjava.util.Collections;5 importjava.util.List;6

7 classUnsupported {8 static void test(String msg, Listlist) {9 System.out.println("--- " + msg + " ---");10 Collection c =list;11 Collection subList = list.subList(1, 8);12 Collection c2 = new ArrayList(subList);13 try{14 c.retainAll(c2);15 System.out.println("retainAll(): SUCCESS!");16 } catch(Exception e) {17 System.out.println("retainAll(): " +e);18 }19 try{20 c.removeAll(c2);21 System.out.println("removeAll(): SUCCESS!");22 } catch(Exception e) {23 System.out.println("removeAll(): " +e);24 }25 try{26 c.clear();27 System.out.println("clear(): SUCCESS!");28 } catch(Exception e) {29 System.out.println("clear(): " +e);30 }31 try{32 c.add("X");33 System.out.println("add(): SUCCESS!");34 } catch(Exception e) {35 System.out.println("add(): " +e);36 }37 try{38 c.addAll(c2);39 System.out.println("addAll(): SUCCESS!");40 } catch(Exception e) {41 System.out.println("addAll(): " +e);42 }43 try{44 c.remove("C");45 System.out.println("remove(): SUCCESS!");46 } catch(Exception e) {47 System.out.println("remove(): " +e);48 }49 try{50 list.set(0, "X");51 System.out.println("List.set(): SUCCESS!");52 } catch(Exception e) {53 System.out.println("List.set(): " +e);54 }55 }56 }57

58 public classTest6 {59 public static voidmain(String[] args) {60 List list = Arrays.asList("A B C D E F G H I J K L".split(" "));61 Unsupported.test("Modifiable Copy", new ArrayList(list));62 Unsupported.test("Arrays.asList()", list);63 Unsupported.test("unmodifiableList()", Collections.unmodifiableList(new ArrayList(list)));64 //Output:65 //--- Modifiable Copy ---66 //retainAll(): SUCCESS!67 //removeAll(): SUCCESS!68 //clear(): SUCCESS!69 //add(): SUCCESS!70 //addAll(): SUCCESS!71 //remove(): SUCCESS!72 //List.set(): SUCCESS!73 //--- Arrays.asList() ---74 //retainAll(): java.lang.UnsupportedOperationException75 //removeAll(): java.lang.UnsupportedOperationException76 //clear(): java.lang.UnsupportedOperationException77 //add(): java.lang.UnsupportedOperationException78 //addAll(): java.lang.UnsupportedOperationException79 //remove(): java.lang.UnsupportedOperationException80 //List.set(): SUCCESS!81 //--- unmodifiableList() ---82 //retainAll(): java.lang.UnsupportedOperationException83 //removeAll(): java.lang.UnsupportedOperationException84 //clear(): java.lang.UnsupportedOperationException85 //add(): java.lang.UnsupportedOperationException86 //addAll(): java.lang.UnsupportedOperationException87 //remove(): java.lang.UnsupportedOperationException88 //List.set(): java.lang.UnsupportedOperationException

89 }90 }