请教一个ListIterator的问题

suuare 2015-10-30 09:14:37
实现将lst2装入lst1内容的反向内容,它们都是ArrayList容器。我使用ListIterator来完成
		
List<Integer> lst1 = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
List<Integer> lst2 = new ArrayList<Integer>(lst1);

ListIterator<Integer> it1 = lst1.listIterator();
ListIterator<Integer> it2 = lst2.listIterator(lst2.size());
//这里如果改为ListIterator<Integer> it2 = lst2.listIterator(lst2.size() - 1);
//那么下面这句it2.previous();就不需要了,但是程序运行时会抛出IllegalStateException异常......
it2.previous();
while (it1.hasNext())
{
Integer integer = (Integer) it1.next();
it2.set(integer);
if(it2.hasPrevious())//如果没有这个限制,也会抛出IllegalStateException异常......
//按理来说容器的长度都相等,一个迭代器指向源的最前面,另一个指向目标的最后,那么循环次数应该相等的啊!
it2.previous();
}
...全文
92 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
解开者 2015-10-30
  • 打赏
  • 举报
回复
如果只是反序的话不用这么写……
        List<Integer> lst1 = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
		List<Integer> lst2 = new ArrayList<Integer>(lst1);
		Collections.reverse(lst2);
		System.out.println(lst2);
soton_dolphin 2015-10-30
  • 打赏
  • 举报
回复
Note that the remove() and set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last element returned by a call to next() or previous().
引用
void set(E e) Replaces the last element returned by next() or previous() with the specified element (optional operation). This call can be made only if neither remove() nor add(E) have been called after the last call to next or previous.
soton_dolphin 2015-10-30
  • 打赏
  • 举报
回复
你的程序应该这么改一下


ListIterator<Integer> it1 = lst1.listIterator();       
        ListIterator<Integer> it2 = lst2.listIterator(lst2.size());
        while (it1.hasNext() && it2.hasPrevious())
        {
            Integer integer = (Integer) it1.next();           
            it2.previous(); // 先拿到这个元素
            it2.set(integer); // 再修改值
        }
soton_dolphin 2015-10-30
  • 打赏
  • 举报
回复
为什么要这么复杂啊。。。

for(int i = list1.size() - 1; i>=0; i--){
		 list2.add(list1.get(i));
		}
}

62,614

社区成员

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

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