增强for循环
增强for循环(也称for each循环)是JDK1.5以后出来的一个高级for循环,专门用来遍历数组和集合的。它的内部原理其实是个Iterator迭代器,所以在遍历的过程中,不能对集合中的元素进行增删操作。
格式:
复制代码
1
2
3
4for(元素的数据类型 变量 : Collection集合or数组){ //写操作代码 }
它用于遍历Collection和数组。通常只进行遍历元素,不要在遍历的过程中对集合元素进行增删操作。
遍历数组
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20public class NBForDemo1 { public static void main(String[] args) { //一维数组 int[] arr = {3,5,6,87}; //使用增强for遍历数组 for(int a : arr){//a代表数组中的每个元素 System.out.println(a); } //二位数组 int[][] array2 = new int[12][10]; //二维数组可以看作是一维数组组成的数组, //所以单array2看作是一维数组,每个元素又是一个数组,用int[]接收 for(int[] len : array2){ for(int col : len){ System.out.println(col); } } } }
遍历集合
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14public class Demo04IteratorFor { public static void main(String[] args) { Collection<String> redVelvet = new ArrayList<>(); redVelvet.add("Irene"); redVelvet.add("Seulgi"); redVelvet.add("Wendy"); redVelvet.add("Joy"); redVelvet.add("Yeri"); for(String str : redVelvet){ System.out.println(str); } } }
tips: 新for循环必须有被遍历的目标。目标只能是Collection或者是数组。新式for仅仅作为遍历操作出现。
最后
以上就是淡然冷风最近收集整理的关于Java中基于Iterator迭代器的增强for循环的全部内容,更多相关Java中基于Iterator迭代器内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复