I believe that I noticed that for certain Iterables (such as the IterableString class ), either a new iterator is created, or the iterator somehow resets to begin with each new foreach construct, but this is not like other Iterators ...
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 from where it stopped (after the last element), but the second foreach loop with y seems to start from where it first started (in the first element). Why is this and how can we make Iterables that behave like the last (ArrayLists)?
More specifically, how exactly would we modify a class such as IterableString to work as an ArrayList?
source share