The Iterable interface

The Iterable interface has a strong relation to the Iterator. The Iterator is an interface used to get items from a collection, one at a time. It follows the fail-fast principles to immediately report whether the iterating collection was modified. The Iterator has a property called current, which is used to return a currently pointed element. The Iterator is initially positioned before the first element in a collection. The moveNext method returns true if there is a next element in the collection and false if not. Before using the Iterator, it must be initialized with the moveNext method to point it to the first element. In the following code, we don't initialize the Iterator with the moveNext method:

void main() {
  List<String> colors = ['red', 'green', 'blue'];
  
  Iterator<String> iter = colors.iterator;
  do  {
    print(iter.current);
  } while (iter.moveNext());
}

The result of this code is unspecified, but it can return null or generate an exception, as shown in the following code:

null
red
green
blue

Note

Always initialize the Iterator with the moveNext method to prevent unpredictable results.

Here is an example that shows you how to use the Iterator properly:

void main() {
  List<String> colors = ['red', 'green', 'blue'];
  
  Iterator<String> iter = colors.iterator;
  while (iter.moveNext()) {
    print(iter.current);
  }
}

The result is as expected:

red
green
blue

Invocation of the moveNext method returns false after the collection ends, and the current pointer always returns the last element.

The for loop statement uses the Iterator transparently to iterate through the collection:

void main() {
  List<String> colors = ['red', 'green', 'blue'];
  
  for (String color in colors) {
    print(color);
  }
}

The result is similar to that of the preceding example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.2.157