使用foreach循环遍历集合元素
生活随笔
收集整理的这篇文章主要介绍了
使用foreach循环遍历集合元素
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
使用foreach循环遍历集合元素
代码实现
import java.util.ArrayList; import java.util.Collection; import java.util.Date; /** jdk5.0新增了foreach循环,用于遍历集合,数组*/ public class ForTest {public static void main(String[] args) {Collection coll = new ArrayList();coll.add(123);coll.add(new Date());coll.add("heipapap");coll.add("baibai");coll.add(false);coll.add(new Person("Tom",23));coll.add(new Person("maruya",23));//for(集合元素的类型 局部变量 : 集合对象)//内部仍然调用了迭代器for(Object obj:coll){System.out.println(obj);}int[] arr = new int[]{1,2,3,4,5,6,7,8};//for(数组元素的类型 局部变量 :数组对象)for(int i :arr){System.out.println(i);}//通过一个练习题来理解一下增强for循环和普通for循环的区别//方式一 普通for循环String[] str = new String[]{"gege","gege","gege"};for(int i =0;i<str.length;i++){str[i]="woc";}//遍历for(int i =0;i<str.length;i++){System.out.println(str[i]);//woc//woc//woc}//方式二:增强for循环for(String s : str){s = "hahaha";}//遍历for(int i =0;i<str.length;i++){System.out.println(str[i]);//woc//woc//woc}} }总结
以上是生活随笔为你收集整理的使用foreach循环遍历集合元素的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Spring入门hello world常
- 下一篇: 将Jquery序列化后的表单值转换成Js