普通For循环:
int [] a ={1,2,3,4,5};
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
增强型For循环:
for(int element : a){
System.out.println(element);
}
两者效果是一样的,但是增强型For循环更简洁,使用更方便!
例:遍历二维数组
int[ ] [ ] arr = {{1,2,3},{4,5,6}{7,8,9}}
for(int[ ] row : arr){
for(int element : row){
System.out.println(element);
}
}
***********************************
**遍历Arrylist**
Arrylist<String> arr = new Arrylist<String>();
arr.add(“阿斯顿”);
arr.add(“马丁”);
for(String element : arr){
System.out.println(element);
}
缺点:无法指定特定元素!!失去了索引!!!
当遍历集合或数组时,如果需要访问集合或数组的下标,那么最好使用旧式的方式;来实现循环或遍历,而不要使用增强For循环,因为它丢失了下标信息!!
1032

被折叠的 条评论
为什么被折叠?



