List<Integer> set = Arrays.asList(1,1,11,111); set.add(55);//(1) set.remove(2);//(2) 结果:java.lang.UnsupportedOperationException (1)(2)是发生错误的地方 疑问:怎么会发生错误呢,List不是会自动变化长度吗
Arrays.asList()返回的List是Arrays工具类的内部类,是只读的,不能新增和删除。查看jdk可以看到asList()里是把数据放到private final E[] a;里的,final修饰的数组,长度是固定的。
ArrayList.asList 返回的是Arrays中的一个内部类,你可以List set = new ArrsyList(Arrays.asList(1,1,11,111));
以下摘录自JAVA API:
public static List asList(T... a)
Returns a [i][u][b]fixed-size[/b][/u][/i] list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.
This method also provides a convenient way to create a fixed-size list initialized to contain several elements
由此可知该方法获得的List是fixed-size大小固定的,所以这些方法都会报错。