遍历集合或数组是平时操作很常用的,之前也没有真正的总结过,如今整理了一下,加上以往使用上的借鉴整理如下,如有写的不完善的地方请指正,谢谢!
整体来说:
增强型for循环使用起来比较方便,代码也比较简单,如果只是操作集合中元素的而不使用索引的话,建议用此方法。
对于普通for循环,如果需要使用索引进行其它操作的话,建议用这个。
详细来说:
1,区别:
增强for循环必须有被遍历的目标(如集合或数组)。
普通for循环遍历数组的时候需要索引。
增强for循环不能获取下标,所以遍历数组时最好使用普通for循环。
2,特点:
书写简洁。
对集合进行遍历,只能获取集合元素,不能对集合进行操作,类似迭代器的简写形式,但是迭代器可以对元素进行remove操作(ListIterator可以进行增删改查的操作)。
3,格式:
for(数据类型变量名 :被遍历的集合(collection)或者数组) {
执行语句
}
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ForTest { public static void main(String[] args) { // TODO Auto-generated method stub /* 1.普通数组中的使用 */ int array[] = { 1,2,3,4,5,6,7,8,9}; // 增强for循环 for (int item : array) { System.out.println(item); } // 普通for循环 for (int i = 0; i < array.length; i++) System.out.println(array[i]); /* 2.二维数组中的使用 */ int array2[][] = {{1,2,3}, {4,5,6}, {7,8,9} }; // 增强for循环 for (int arr[] : array2) { for (int item : arr) { System.out.println(item); } } // 普通for循环 for (int i = 0; i < array2.length; i++) { for (int j = 0; j < array2[i].length; j++) { System.out.println(array2[i][j]); } } /* 3.List中的使用 */ List<String> list = new ArrayList<String>(); list.add("我"); list.add("爱"); list.add("中"); list.add("国"); // 增强for循环 for (String item : list){ System.out.println(item); } //普通for循环 for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } //迭代器遍历 Iterator<String> it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
最后
以上就是追寻芹菜最近收集整理的关于增强型for循环和普通for循环在使用上的区别的全部内容,更多相关增强型for循环和普通for循环在使用上内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复