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+
Since you seem to be using lists, the simplest solution in your case is to use two indexes, something like this:
for (int i = 0; i < aList.size(); i++) {
for (int j = i; j < aList.size(); j++) {
// do stuff with aList's elements
aList.get(j);
}
}
With iterators, you can achieve similar things, but you have to construct new iterators for the inner loop, possibly from
aList.subList(i, aList.size()).iterator();
Do this:
ArrayList<String> aList = new ArrayList<String>();
// do something to fill the list
for (int i = 0; i < aList.size(); i++)
{
ArrayList<String> bList = aList.subList(i, aList.size());
for (int j = 0; j < bList.size(); j++)
{
// do stuff with the sublist
}
}
It's important to note that bList is backed by aList so changes to bList will be reflected in aList...make non-structural changes only to keep your sanity.
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);
It's valid, but it won't do what you want it to do. You'll still have only one iterator, and the outer loop will terminate after the inner one has terminated for the first time.
Java iterators cannot be copied meaningfully. You'll have to use a simple for loop that increments indexes.