我是靠谱客的博主 高兴鸡翅,这篇文章主要介绍Java中关于foreach的用法,现在分享给大家,希望可以做个参考。

foreach的语句格式:
for(元素类型t 元素变量x : 遍历对象obj){
引用了x的java语句;
}
foreach比for的好处和弊端
好处:相对于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
public class ForEachDemo { public static void main(String[] args) { funciton_2(); // testHashSet(); } public static void funciton_2() { ArrayList<Person> arr = new ArrayList<Person>(); arr.add(new Person("a", 18)); arr.add(new Person("b", 18)); for (Person p : arr) { System.out.println(p); } } public static void testHashSet() { Collection<String> coll = new ArrayList<String>(); coll.add("abc1"); coll.add("add2"); coll.add("add3"); coll.add("add4"); coll.add("add5"); coll.add("add6"); for (String s : coll) { System.out.println(s); } } public static void function_1() { String[] str = { "abc", "a2bb", "a2aa" }; for (String s : str) { System.out.println(s.length()); System.out.println(s); } } public static void function() { int[] arr = { 2121, 5454, 545, 4, 54 }; for (int i : arr) { System.out.println(i); } } } ———————————————— 版权声明:本文为CSDN博主「Fanlei的技术栈」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_35849955/article/details/82527693

最后

以上就是高兴鸡翅最近收集整理的关于Java中关于foreach的用法的全部内容,更多相关Java中关于foreach内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部