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:
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.
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...
If you want a second list iterator at position n in the list then use List#listIterator(int index):
ListIterator bIter = list.listIterator(n);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With