public class AddingGroups { public static void main(String[] args) { Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5)); Integer[] moreInts = {6,7,8,9,10}; collection.addAll(Arrays.asList(moreInts)); Collections.addAll(collection, 11,12,13,14,15); Collections.addAll(collection, moreInts); List<Integer> list = Arrays.asList(16,17,18,19,20); list.set(1, 99); list.add(21); //Runtime error because the underlying array cannot be resized. } }
此段代码编译时最后一行出错。
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.javabase.chapternine.AddingGroups.main(AddingGroups.java:21)
直接使用Arrays.asList()的输出,将其当作List,但是在这种情况下,其底层表示的是数组,因此不能调整尺寸。如果你试图用add()或delete()方法在这种列表中添加或删除元素,就有可能会引发去改变数组尺寸的尝试,因此你将在运行时获得“Unsupported Operation(不支持的操作)”错误。
Arrays.asList()方法的限制是它对所产生的List的类型做出了最理想的假设,而并没有注意你对它会赋予什么样的类型