Arrays.asList给出UnsupportedOperationException
无法使用add
或remove
等方法修改Arrays.asList
返回的List
。 但是如果将它传递给Collections.sort
方法,它可以对数组进行排序而没有任何问题(我预计会有exception)。 这似乎是一种非常不一致的行为。 那么什么是List
上允许的操作,由asList
方法返回?
List list = Arrays.asList(5,7, 10 , 8,9); list.remove(2);//Exception Collections.sort(list);//Ok, No Exception Sort... System.out.println(list);
我在文档中找不到任何线索。
编辑:是的我可以理解为什么它不支持remove
或add
。 但那么它如何支持排序呢?
Arrays.asList
返回由数组支持的固定大小List
。 因此不支持remove
和add
。 支持。 您可以查看此List
,就好像它的行为与数组完全一样。 数组具有固定长度。 您不能添加或删除元素,但可以为数组的索引赋值,这相当于List
的set
方法。 你可以对数组进行排序。
Collections.sort(list)
不会更改List
的大小,因此可以对固定大小的列表进行排序。 为了对List
进行排序,您只需要交换List
元素。 为此目的, set(index,element)
就足够了。
所有这些信息都可以在Javadoc of Arrays
:
/** * Returns a fixed-size 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 {@link Collection#toArray}. The returned list is * serializable and implements {@link RandomAccess}. * *
This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: *
* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); ** * @param a the array by which the list will be backed * @return a list view of the specified array */ public static
List asList(T... a) 如果你看一下
Collections.sort
的实现,你会发现它实际上对一个数组进行了排序。 它要求修改List
的唯一List
方法是List
的ListIterator
,它调用List
的set(index,element)
方法。public static
> void sort(List list) { Object[] a = list.toArray(); Arrays.sort(a); ListIterator i = list.listIterator(); for (int j=0; j
Arrays.asList
为您提供由您提供的数组支持的List
。 数组是固定大小的。 包装List
支持与数组相同的操作,因此您可以重新分配条目,但不能更改其长度。