I believe I've noticed that for certain Iterables (such as this IterableString class) either a new iterator is created or the iterator somehow resets to the start with every new foreach construct but that this does not seem to occur with other Iterables...
For example, if you run the following code:
import java.util.ArrayList;
public class test {
public static void main(String args[]) {
IterableString x = new IterableString("ONCE");
System.out.println("***");
for (char ch : x){
System.out.println(ch);
}
System.out.println("***");
for (char ch : x){
System.out.println(ch);
}
ArrayList y = new ArrayList();
y.add('T');
y.add('W');
y.add('I');
y.add('C');
y.add('E');
System.out.println("***");
for (char ch : y){
System.out.println(ch);
}
System.out.println("***");
for (char ch : y){
System.out.println(ch);
}
System.out.println();
}
}
you will see the following output:
***
O
N
C
E
***
***
T
W
I
C
E
***
T
W
I
C
E
The second foreach loop with x seems to start off where it left off (after the last item), but the second foreach loop with y seems to start from the where it started the first time (at the first item). Why is this and how can we make Iterables that behave like the latter (ArrayLists)?
More concretely, how exactly would we modify a class like IterableString to work like the ArrayList?
The class IterableString
(as defined by your linked article) is both the Iterable
and the Iterator
. Whether or not that's a good idea is debatable - but a simple fix is:
// This method implements Iterable.
public Iterator<Character> iterator() {
return new IterableString(this.str);
}
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