未获支持操作:
因为没种容器背后都是由固定尺寸的数据机构支持的,所以在不同的容器中有些操作是不支持的 (UnsupportedOperationExcetion).
①:Arrays.asList{}
会生成一个List,但他是基于一个大小固定的数组。所以任何会改变数组大小的操作都是未获支持的。
②:Collections.unmodifiableList();
产生一个不可修改的列表,只支持读取。不支持任何修改元素的操作。
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);
Collection<String> c2 = new ArrayList<>(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);
}
// The List.set() method modifies the value but
// doesn't change the size of the data structure:
try {
list.set(0, "X");
} catch(Exception e) {
System.out.println("List.set(): " + 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(" "));
//经过ArrayList包裹的类 支持全部的操作
ArrayList<String> arrayList = new ArrayList<>(list);
//未包装的list 仅支持只读和修改的操作
//test("Arrays.asList()", list);
//System.out.println(list);
List<String> unmodifiableList = Collections.unmodifiableList(new ArrayList<String>(list));
//仅支持只读操作,修改也不支持
test("unmodifiableList()", unmodifiableList);
System.out.println(unmodifiableList);
}
}