從Java 5(例如,JDK 1.5或者J2SE 5)起,出現了for循環的改進版。
格式爲
for (type iteration-variable:iterableObject)
constituent statement
或者
for (type iteration-variable:iterableObject){
constituent statement
}
這種寫法稱爲for each,意思就是對type類型的數組或集合iterableObject進行遍歷。
下面舉例說明
for (IntWritable val : values){
sum += val.get();
}
for(int i = 0; i<values.length; i++){
sum=sum+values[i]; //對values[i]求和
}