list 的迭代器不支持set方法

yuxinjian 2014-11-16 09:29:51
请教一个关于java中
Collections.sort的一个问题。
(即public static <T extends Comparable<? super T>> void sort(List<T> list))
我在jdk api 中看到:UnsupportedOperationException - if the specified list's list-iterator does not support the set operation.
这句话是什么意思?什么叫list 的迭代器不支持set方法?set方法是指什么?能详细的解释一下么?
或者能有什么例子,能在调用这个sort方法的时候,抛出这个UnsupportedOperationException 异常?
...全文
252 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wyc_ 2014-11-16
  • 打赏
  • 举报
回复
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操作才能排序
wyc_ 2014-11-16
  • 打赏
  • 举报
回复
引用 3 楼 yuxinjian 的回复:
我看了api文档中的ListIterator接口,发现它里边就有set方法,那为什么说if the specified list's list-iterator does not support the set operation.。是不是我理解有偏差?我是初学者,如果理解有偏差,还请谅解。
ArrayList中的源码:
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();
	}
}
yuxinjian 2014-11-16
  • 打赏
  • 举报
回复
我看了api文档中的ListIterator接口,发现它里边就有set方法,那为什么说if the specified list's list-iterator does not support the set operation.。是不是我理解有偏差?我是初学者,如果理解有偏差,还请谅解。
yuxinjian 2014-11-16
  • 打赏
  • 举报
回复
我看了listIterator接口,它里边就有这个set方法。说明它是支持set方法的。那为什么说if the specified list's list-iterator does not support the set operation.?还是我哪边理解有问题?我是初学者,如果理解得有偏差,还请包涵。

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧