Arrays.asList会引发UnsupportedOperationException异常。

9

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。但是它如何支持排序呢?
2个回答

12
Arrays.asList 返回一个由数组支持的固定大小的 List。因此,不支持 removeadd 操作,但支持 set 方法。你可以把这个 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方法是ListIteratorset方法,该方法调用了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]);
  }
}

1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Durandal

2

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接