Reputation: 63
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?
Upvotes: 6
Views: 1540
Reputation: 16605
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);
}
Upvotes: 5
Reputation: 2461
An ArrayList
is able to be iterated over in a java foreach loop because it implements the Iterable
interface in Java. The Iterable
interface outlines a method iterator
which returns an iterator for the collection. Using a foreach loop in java uses the iterator from this method under the hood. Every time you create a new foreach loop, the ArrayList
is providing a new iterator.
If you want to create a class that can be iterated over using a foreach loop in Java, you need to implement the Iterable
interface and define how to iterate over the collection.
Upvotes: -1