共计 1018 个字符,预计需要花费 3 分钟才能阅读完成。
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); | |
} | |
} |
正文完
星哥玩云-微信公众号
