背景
foreach是java语言的特征之一,主用于遍历数组、集合方面,提供了很大的方便。
foreach语句是for语句的简化版本,但是却不能完全的代替他,但是foreach语句可以理解为是for语句的工具版
简述
foreach并不是一个关键字,而是习惯将这种语法格式称之为foreach语句,从英文的字面意思可以理解为“每一个for”语句。
格式
foreach语句格式:
for(元素类型T 元素变量x:遍历对象obj){
引用了x的java语句;
}
利弊
相对于for而言方便了对于容器的遍历,但因为没有索引,不能够操作元素中的元素。
代码示例
复制代码
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
61
62
63
64
65public class ForEachDemo { // 主方法接口 public static void main(String[] args) { function(); function_1(); funciton_2(); testHashSet(); } public static void function() { // 创建一个int数组 int[] arr = { 2121, 5454, 545, 4, 54 }; // 验证 for (int i : arr) { System.out.println(i); } } public static void function_1() { // 创建一个String数组 String[] str = { "abc", "a2bb", "a2aa" }; // 验证 for (String s : str) { System.out.println(s.length()); System.out.println(s); } } public static void funciton_2() { // 创建一个ArrayList集合 ArrayList<Person> arr = new ArrayList<Person>(); arr.add(new Person("a", 18)); arr.add(new Person("b", 18)); // 测试foreach语句 for (Person p : arr) { System.out.println(p); } } // 测试foreach语句 public static void testHashSet() { // 创建一个Collection单列集合集合 Collection<String> coll = new ArrayList<String>(); coll.add("abc1"); coll.add("add2"); coll.add("add3"); coll.add("add4"); coll.add("add5"); coll.add("add6"); // 测试foreach语句 for (String s : coll) { System.out.println(s); } } }
最后
以上就是隐形黑裤最近收集整理的关于JavaSE之ForEach循环遍历的全部内容,更多相关JavaSE之ForEach循环遍历内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复