Java Iterables "Reset" Iterator with Each Foreach Construction

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?

+6
source share
2 answers

The IterableString class (as defined by your related article ) is both Iterable and Iterator . Regardless of whether this idea is a good discussion, but a simple fix:

  // This method implements Iterable. public Iterator<Character> iterator() { return new IterableString(this.str); } 
+4
source

An ArrayList can be repeated in a java foreach loop as it implements the Iterable interface in Java. The Iterable interface describes an iterator method that returns an iterator for a collection. Using the foreach loop in java uses the iterator from this method under the hood. Each time you create a new foreach loop, ArrayList provides a new iterator.

If you want to create a class that can be repeated using the foreach loop in Java, you need to implement the Iterable interface and determine how to iterate through the collection.

-1
source

All Articles