When you write a for-each loop like for (String s : list), Java calls the iterator() method behind the scenes. This method comes from the Iterable<T> interface.
The Iterator object it returns has methods you need to know:
hasNext()returnstrueif more elements remainnext()returns the next element
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
If your own class implements Iterable<T>, it becomes usable in for-each loops. You just return an Iterator from the iterator() method, and Java handles the rest.