Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using two iterators in one ArrayList

Tags:

java

iterator

Edit: 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.

Some notes:

  • The second iterator should start from the position befind the first iterator.
  • I try to go through an ordered list starts form the beginning, find some objects down the list which has similar properties as the one pointed by aItr.

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.

Hi,

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.

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.

like image 954
EXP0 Avatar asked Dec 04 '22 08:12

EXP0


2 Answers

You shouldn't do:

Iterator bIter = aIter;

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

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()) {
   // ...
 }
}

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

like image 72
Dilum Ranatunga Avatar answered Dec 06 '22 09:12

Dilum Ranatunga


If you want a second list iterator at position n in the list then use List#listIterator(int index):

ListIterator bIter = list.listIterator(n);
like image 23
anubhava Avatar answered Dec 06 '22 11:12

anubhava