您好,欢迎访问一九零五行业门户网

浅谈java 增强型的for循环 for each

for-each循环
for-each循环也叫增强型的for循环,或者叫foreach循环。
for-each循环是jdk5.0的新特性(其他新特性比如泛型、自动装箱等)。
for-each循环的加入简化了集合的遍历。
其语法如下:
for(type element: array) { system.out.println(element); }
例子
其基本使用可以直接看代码:
代码中首先对比了两种for循环;之后实现了用增强for循环遍历二维数组;最后采用三种方式遍历了一个list集合。
import java.util.arraylist; import java.util.iterator; import java.util.list; public class foreachtest { public static void main(string[] args) { int[] arr = {1, 2, 3, 4, 5}; system.out.println("----------旧方式遍历------------"); //旧式方式 for(int i=0; i<arr.length; i++) { system.out.println(arr[i]); } system.out.println("---------新方式遍历-------------"); //新式写法,增强的for循环 for(int element:arr) { system.out.println(element); } system.out.println("---------遍历二维数组-------------"); //遍历二维数组 int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} ; for(int[] row : arr2) { for(int element : row) { system.out.println(element); } } //以三种方式遍历集合list list<string> list = new arraylist<string>(); list.add("a"); list.add("b"); list.add("c"); system.out.println("----------方式1-----------"); //第一种方式,普通for循环 for(int i = 0; i < list.size(); i++) { system.out.println(list.get(i)); } system.out.println("----------方式2-----------"); //第二种方式,使用迭代器 for(iterator<string> iter = list.iterator(); iter.hasnext();) { system.out.println(iter.next()); } system.out.println("----------方式3-----------"); //第三种方式,使用增强型的for循环 for(string str: list) { system.out.println(str); } } }
for-each循环的缺点:丢掉了索引信息。
当遍历集合或数组时,如果需要访问集合或数组的下标,那么最好使用旧式的方式来实现循环或遍历,而不要使用增强的for循环,因为它丢失了下标信息。
以上就是小编为大家带来的浅谈java 增强型的for循环 for each的全部内容了,希望对大家有所帮助,多多支持~
更多浅谈java 增强型的for循环 for each。
其它类似信息

推荐信息