从开始接触Java编程时,简单的循环遍历(for、while、do…while)都是与其他编程语言(C语言、C++… …)大致一样的,这些我们自己都看得懂,当然自己也会写。但是学习到后面的课程,当听到一个词“增强for循环”,是不是有点懵?前面本人确实没有了解过,导致我看源码或者别人写的代码的时候,确实会有“这玩意儿到底是啥?”的赶脚!其实就是我没有掌握java jdk5.0新增的特性而已,接下来对增强型for循环做详细的说明与介绍。
目录
- 1. 定义
- 2. 遍历集合
- 3. 遍历数组
- 4. 区分普通for循环和增强for循环
1. 定义
Java jdk5.0新增了foreach循环,用来遍历集合、数组,这就是所谓的增强for循环。
2. 遍历集合
for(集合元素的类型 局部变量 : 集合对象)内部代码仍然调用迭代器for(Object obj : coll){System.out.println(obj);}
@Testpublic void test1(){Collection coll = new ArrayList();coll.add(123);coll.add(456);coll.add(new String("Tom"));coll.add(new Person("Jerry",25));coll.add(false);for(Object obj : coll){System.out.println(obj);}}
3. 遍历数组
for(数组元素的类型 局部变量 : 数组对象)for (int i : arr){System.out.println(i);}
@Testpublic void test2(){int[] arr = new int[]{1,2,3,4,5};for (int i : arr){System.out.println(i);}}
4. 区分普通for循环和增强for循环
(一):增强for循环,不改变arr[]的值例:for (String s : arr){s = "GG";}(二):普通for循环,改变了arr[]中的值例:for (int i = 0; i < arr.length; i++) {arr[i] = "GG";}
@Testpublic void test3(){String[] arr = new String[]{"MM","MM","MM"};for (String s : arr){s = "GG";}for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}for (int i = 0; i < arr.length; i++) {arr[i] = "GG";}for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}}
@Testpublic void test4(){String[] str = new String[5];for (String myStr : str) {myStr = "hao";System.out.println(myStr);//五个"hao"}for (int i = 0; i < str.length; i++) {System.out.println(str[i]);//五个“null”}}
从上面实例的输出的结果也可以看出,增强型for循环内部用输出语句输出时能显示五个“hao”,由于增强型for循环是不改变数组本身的元素值,所以在外部用普通for循环输出的为“null”,进而验证了两个循环之间的区别所在!
路过的小伙伴,如果博文有帮助到你解决问题,可以点赞+关注一波呀~本人将会持续更新相关学习博文,感谢您的支持哦!!!