Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Iterables "Resetting" Iterator With Every Foreach Construct

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?

like image 263
user1920345 Avatar asked Dec 21 '12 01:12

user1920345


1 Answers

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);
  }
like image 102
Greg Kopff Avatar answered Oct 23 '22 04:10

Greg Kopff