62,620
社区成员
发帖
与我相关
我的任务
分享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]);
}
}
看一下源码就知道了,它是先把List转为数组排序,然后再设置回List中,所以必须支持set操作才能排序private class ListItr extends Itr implements ListIterator<E> {
。。。。。。。省略其他方法。。。。
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
这说明它实现了ListIterator,包括其中的set方法,所以它可以排序,但是我也可以自己写一个类继承List,而在里面我可以这样实现ListIterator,set方法可以什么都不写,或者直接抛出异常,表示不支持set。如下
private class ListItr extends Itr implements ListIterator<E> {
。。。。。。。省略其他方法。。。。
public void set(E e) {
//throw new UnsupportedOperationException();
}
}