Java – How to use the java for each loop with custom classes


I think most coders have used code like the following :

ArrayList<String> myStringList = getStringList();
for(String str : myStringList)

How can I take advantage of the for each loop with my own classes? Is there an interface I should be implementing?

Best Solution

You can implement Iterable.

Here's an example. It's not the best, as the object is its own iterator. However it should give you an idea as to what's going on.