The List
由返回Arrays.asList
不能通过使用诸如add
or remove
。但如果你把它传递给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);
我在文档中找不到任何线索。
Edit:是的,我明白为什么它不支持remove
or add
。那么它怎么支持排序呢?
Arrays.asList
返回固定大小List
由数组支持。所以remove
and add
不支持。set
是支持的。你可以看看这个List
就好像它的行为与数组完全相同。数组具有固定长度。不能添加或删除元素,但可以为数组的索引赋值,这相当于set
的方法List
。并且您可以对数组进行排序。
Collections.sort(list)
不改变的大小List
,所以可以对固定大小的列表进行排序。排序所需的一切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<String> 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
is set
of the List
's ListIterator
,这称为List
's set(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]);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)