组团学

增强For循环(foreach)

阅读 (834027)

1、遍历数组

1.1、格式

for (Type value : array) { expression value; }

1.2、案例

public class ForeachDemo01 { public static void main(String args[]){ //for int[] array = {1,2,5,8,9}; int total = 0; for (int i = 0; i < array.length; i++){ total += array[i]; } System.out.println(total); //foreach total = 0; for (int n : array) { total += n; } System.out.println(total); } }

这种循环的缺点是:

(1)只能顺序遍历所有元素,无法实现较为复杂的循环,如在某些条件下需要后退到之前遍历过的某个元素,不能完成

(2)循环变量(i)不可见,不能知道当前遍历到数组的第几个元素

2、遍历集合

2.1、格式

for (Type value : Iterable) { expression value; }

注意:foreach循环遍历的集合必须是实现Iterable接口的。

2.2、案例

public class ForeachDemo02 { public static void main(String[] args) { someFunction01(); someFunction02(); } //以前我们这样写: static void someFunction01(){ List list = new ArrayList(); list.add("Hello "); list.add("Java "); list.add("World!"); String s = ""; for (Iterator iter = list.iterator(); iter.hasNext();){ String temp= (String) iter.next(); s += temp; } System.out.println(s); } //现在我们这样写: static void someFunction02(){ List list = new ArrayList(); list.add("Hello "); list.add("Java "); list.add("World!"); String s = ""; for (Object o : list){ String temp = (String) o; s += temp; } System.out.println(s); } }
需要 登录 才可以提问哦