Arrays.asList给出UnsupportedOperationException

Sam*_*gha 5 java collections

List通过返回Arrays.asList不能通过使用方法如被修改addremove.但是如果你将它传递给Collections.sort方法,它可以毫无问题地对数组进行排序(我预计会有例外).这似乎是一种非常不一致的行为.那么方法List返回的允许操作是什么asList

List<Integer> list = Arrays.asList(5,7, 10 , 8,9);
list.remove(2);//Exception

Collections.sort(list);//Ok, No Exception Sort...
System.out.println(list);
Run Code Online (Sandbox Code Playgroud)

我在文档中找不到任何线索.

编辑:是的我可以理解为什么它不支持removeadd.但那么它如何支持排序呢?

Era*_*ran 12

Arrays.asList返回List由数组支持的固定大小.因此remove,add不受支持.set得到支持.您可以将其List视为与数组完全相同的行为.数组具有固定长度.您不能添加或删除元素,但可以为数组的索引赋值,这相当于set方法List.你可以对数组进行排序.

Collections.sort(list)不会改变大小List,因此可以对固定大小的列表进行排序.为了对a进行排序所需要的List只是交换元素List.为此目的set(index,element)就足够了.

所有这些信息都可以在Javadoc中找到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}.
 *
 * <p>This method also provides a convenient way to create a fixed-size
 * list initialized to contain several elements:
 * <pre>
 *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
 * </pre>
 *
 * @param a the array by which the list will be backed
 * @return a list view of the specified array
 */
 public static <T> List<T> asList(T... a)
Run Code Online (Sandbox Code Playgroud)

如果你看一下它的实现Collections.sort,你会发现它实际上是对一个数组进行排序.唯一的List方法它要求修改的List就是set所述的ListListIterator,它调用Listset(index,element)方法.

public static <T extends Comparable<? super T>> void sort(List<T> list) {
  Object[] a = list.toArray();
  Arrays.sort(a);
  ListIterator<T> i = list.listIterator();
  for (int j=0; j<a.length; j++) {
      i.next();
      i.set((T)a[j]);
  }
}
Run Code Online (Sandbox Code Playgroud)