This method does not appear until after jdk1.5.
1: iterating through an array
Grammar:
for (Type Value:array) {
Expression value;
}
Example:
void Sum ()
{
Int[] array = {1,2,5,8,9};
int sum= 0;
for (int n:array)
{
sum+= N;
}
Disadvantages:
For arrays, it is difficult to access subscript values;
2: Traversing the collection
Grammar:
for (Type value:iterable) {
Expression value;
}
Example:
void Sum ()
{
List List = new ArrayList ();
List.add ("Hello");
List.add ("Java");
List.add ("world!");
String s = "";
for (Object o:list)
{
String temp = (string) o;
s + = temp;
}
The code above will be translated by the compiler to:
void SomeFunction ()
{
List List = new ArrayList ();
List.add ("Hello");
List.add ("Java");
List.add ("world!");
String s = "";
for (Iterator iter = List.iterator (); Iter.hasnext ();)
{
String temp = Iter.next ();
s + = temp;
}
For traversing a collection, it is not good to delete the contents of the collection (because it is internally called Interator) compared to using Interator.
It is not recommended to use an enhanced for loop in addition to simply traversing and reading the contents of it.
Use of enhanced for loop in Java