欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

使用foreach循环遍历集合元素

发布时间:2025/3/15 编程问答 31 豆豆
生活随笔 收集整理的这篇文章主要介绍了 使用foreach循环遍历集合元素 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

使用foreach循环遍历集合元素

  • Java5.0 提供了foreach循环迭代访问Collection和数组
  • 遍历操作不需要获取Collection或数组的长度,无需使用索引访问元素
  • 遍历集合的底层调用Iterator完成操作
  • 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循环遍历集合元素的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。