首页 > 其他 > 详细

增强for循环

时间:2021-05-27 22:35:14      阅读:24      评论:0      收藏:0      [点我收藏+]

增强for循环

增强for循环是JDK1.5以后出来的一个高级for循环,专门用来遍历数组和集合的。他的内部原理其实是个Iterator迭代器,所以在遍历过程中,不能对集合中的元素进行增删操作。

格式:

for(元素的数据类型 变量 : Collection集合 or 数组){
    
}

它用于遍历Collection数组。通常只进行遍历元素,不要在遍历过程中对集合元素进行增删操作。

遍历数组

int[] arr = new int[]{11,22,33};

for (int n : arr) {

  //变量n代表被遍历到的数组元素

  System.out.println(n);

}

遍历集合

Collection<String> coll = new ArrayList<String>();
coll.add("a1");
coll.add("a2");
coll.add("a3");
coll.add("a4");
for(String str : coll){
    //变量Str代表被遍历到的集合元素
    System.out.println(str);
}


增强for循环

原文:https://www.cnblogs.com/cushionzengblog/p/14819452.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!