在一个ArrayList中使用两个迭代器 [英] using two iterators in one ArrayList

查看:530
本文介绍了在一个ArrayList中使用两个迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:感谢您的所有提示回复。现在我看到作业不起作用。从另一个线程我读到,Java中的迭代器比C ++中的迭代器强大得多。请问为什么在Java中使用iterator?只是为了取代for循环?谢谢。

Thank you for all your prompt replies. Now I see the assignment won't work. From another thread I read that iterator in Java is much less powerful than iterator in C++. May I ask then why use iterator in Java? Just to replace "for" loop? Thanks.

一些注释:


  • 第二个迭代器应该从这个位置开始找到第一个迭代器。

  • 我尝试从头开始查看有序列表,在列表中找到一些与aItr指向的属性类似的对象。

我不介意使用两个for循环,但我知道Java对所有这些库都非常强大。我只是好奇是否有比两个for循环更好的方法。谢谢。

I don't mind using two "for" loops, but I know Java is very powerful with all those libraries. I'm just curious if there is any better methods than two "for" loops. Thanks.

我一直在使用C ++,但我是Java的新手所以请忍受与我一起。我尝试使用两个迭代器遍历ArrayList。第一个迭代器遍历列表,第二个迭代器从第一个迭代器指向的位置开始,一直到列表的末尾。以下代码是我想要做的(虽然可能无效):

I've been using C++ but I'm new to Java so please bear with me. I try to loop through an ArrayList with two iterators. The first iterator goes through the list, and the second starts from the position pointed by the first iterator and goes till the end of the list. The following code is what I want to do (maybe invalid though):

.......; //initialize aList here ......
Iterator aItr = aList.iterator();
while(aItr.hasNext()){
     int a = aItr.next();
     Iterator bItr = aItr; //-----> is it valid? Any bad consequence?
     while (bItr.hasNext()){
         ............; //do stuff
     }
}

分配一个迭代器是否有效到另一个?如果没有,那么做我想做的最好的方法是什么?谢谢。

Is it valid to assign one iterator to another? If not, then what is the best way to do what I want to do? Thank you.

我知道它在C ++中有效但不确定Java,我用Google搜索了很多但是所有结果都使用iterator来打印一些东西。非常感谢你的帮助。

I know it's valid in C++ but not sure about Java, and I googled a lot but all the results use iterator just to print something. Thank you very much for your help.

推荐答案

你不应该这样做:

Iterator bIter = aIter;

因为Java中没有复制构造函数等; bIter将是对同一个底层迭代器的引用。

Because there is no copy constructor etc in Java; bIter will be a reference to the same underlying iterator.

可以以这种方式使用ListIterator:

You could use a ListIterator this way:

ListIterator aItr = aList.listIterator();
while (aItr.hasNext()) {
 int a = aItr.next();
 ListIterator bItr = aList.listIterator(aItr.previousIndex());
 while (bItr.hasNext()) {
   // ...
 }
}

但如果你认为ListIterator应该有一个copy()方法或类似的东西,我同意你的看法......

But If you are thinking that ListIterator should have had a copy() method or something along those lines, I agree with you...

这篇关于在一个ArrayList中使用两个迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆