Creating a Custom Iterator in Java

Whenever you use a for-each loop in Java, you are iterating over a class that implements the Iterable interface and that uses a second class that implements the Iterator interface to determine which objects are looped over.

Arrays and most Collection classes handle this behind the scenes. Here’s an example of this in action:

String[] items = new String[] {"abc","def","ghi"};
 
for (String item: item)
    System.out.println(item);

It is fairly straightforward to implement these interfaces for a custom purpose. One example of when this might be useful is when you are dealing with a large amount of data, and it would take too much memory to store the data in an object that is iterable (such as ArrayList). I encountered this recently when I was dealing with extremely large files. Please see this post for an example of how to do this.

Leave a Reply