Arrays.asList 给出 UnsupportedOperationException

Arrays.asList give UnsupportedOperationException

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

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);

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

编辑: 是的,我能理解为什么它不支持 removeadd。但是它怎么支持排序呢?

Arrays.asList returns 由数组支持的固定大小 List。因此不支持 removeaddset 支持。您可以将此 List 看成它的行为与数组完全一样。数组具有固定长度。不能添加或删除元素,但可以为数组的索引赋值,相当于Listset方法。你可以对数组进行排序。

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

所有这些信息都可以在 Arrays 的 Javadoc 中找到:

/**
 * 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)

如果您查看 Collections.sort 的实现,您会发现它实际上对数组进行排序。它要求修改 List 的唯一 List 方法是 ListListIteratorset,它调用 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]);
  }
}

Arrays.asList 给你一个 List 你给它的数组 支持。数组是固定大小的。包装 List 支持与数组相同的操作,因此您可以重新分配条目,但不能更改其长度。