Iterator Pattern

  • aka cursor
  • Example:
    • Interface: java.util.Iterator
      • hasNext(): boolean
      • next(): E
    • For-Each loops use iterator under the hood for Collections
      • For static arrays they use different implementation with normal for-loop
var list = List.of("Hello", "World");
 
// using for-each loop
for (var x:list) {
    System.out.println(x);
}
 
// using iterator
Iterator it=list.iterator();
while (it.hasNext()){
    var x = it.next();
    System.out.println(x);
}

Iterator_Pattern_Definition