First, it can be used with arrays. Consider an array of objects of type MyClass
:
MyClass[] objects = new MyClass[SIZE];
Iterate like so:
for(MyClass object : objects) {
// do something with the individual object.
}
Secondly, you can use it with iterable collections. Consider a class MyClass
of individual elements and make a collection of them by defining a subclass of Iterable
:
class MyClassList implements Iterable<MyClass> {
// define necessary methods to implement the Iterable interface!
}
Now we can make a collection:
MyClassList objects = new MyClassList();
// fill the collection somehow.
And iterate:
for(MyClass object : objects) {
// do something with the individual object
}
Finally, note that the main disadvantage of this construct is that you don't have access to an element's position in the iteration. For a given object
that you are processing, if you want to know its position you should either use a for loop:
for(int i = 0; i < objects.size(); i++) {
// Here we have access to the position i
}
Or use a makeshift index:
int i = 0;
for(MyClass object : objects) {
// do something with access to position i
i++;
}
I personally do not like the last hack, and would just fall back to the classic for
loop. Hope this helps!