This is an example of how it is possible to get the results you want in several different ways. This kind of redundancy is not unique to Java.
- for (int i=0; i < myArray.length; i++) { ... }
This syntax was introduced in the very early versions of Java. It iterates over a usual Java array in a for { } loop. This is generally safe because Java arrays are fixed length and so "Index Out of Bounds" exceptions are not possible.
- for (int i=0; i < myArrayList.size(); i++ { ... }
This syntax reflects a later release of Java, after the introduction of the Collections API which introduced ArrayList. Classes that implement the Collection interface, as already mentioned above, must implement an Iterator but you don't have to use it. This for { } loop doesn't, but the danger here is that ArrayLists are not fixed size. If it should shrink in the body of your for loop, and exception can result.
- for (MyArrayType t : myArrayList) { }
This syntax was also released in a later release of Java. It is called the enhanced for loop. Any collection class that provides an Iterator by implementing the Iterable interface can take advantage of this syntax. This allows iterating over items in a collection without having to explicitly instantiate an Iterator. A favorite way to use this in a JavaFX Application is to loop through a bunch of controls to set a property to a value, eg. to reset the contents of a group of TextFields:
for (TextField tf : new TextField[] { txtf1, txtf2, txtf3, txtfa, txtfb, txtfc}) {
tf.setText("");
}
- while (myCollectionIterator.hasNext()) { }
You can always explicitly instantiate an Iterator. This is safe to use when collection size is changing (from the Collection's own methods). It correct to say that the Iterator is more closely a property of the Iterable interface than a feature of the core Java language. But you can still use it as a language-like feature (in the enhanced for loop) thanks to later Java releases.
These constructs provide redundancy, but they are not identical. There are nuances of each that enable one to be particularly useful at a given time. You should use all of them.