Java 5 之后終于能在java中使用for each 循環(huán)

for (type var : arr)
{
body-of-loop
}







for (int i = 0; i < arr.length; i++)
{
type var = arr[i];
body-of-loop
}







For-each loop | Equivalent for loop |
---|---|
for (type var : arr) { body-of-loop } |
for (int i = 0; i < arr.length; i++) { type var = arr[i]; body-of-loop } |
for (type var : coll) { body-of-loop } |
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) { type var = iter.next(); body-of-loop } |
Where the for-each is appropriate
Altho the enhanced for loop can make code much clearer, it can't be used in some common situations.
- Only access. Elements can not be assigned to, eg, not to increment each element in a collection.
- Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays.
- Only single element. Use only for single element access, eg, not to compare successive elements.
- Only forward. It's possible to iterate only forward by single steps.
- At least Java 5. Don't use it if you need compatibility with versions before Java 5.
看來只能讀取, 而不能寫入值。而且不能進(jìn)行太復(fù)雜的操作。