Java–foreach循环
foreach是Java5新增,在遍历数组,集合的时候有不错的性能.
- foreach的语法格式:
复制代码
1
2
3
4for(元素类型 每次循环的元素名称 : 循环对象){ }
一.常见的使用方式
1.遍历数组
复制代码
1
2
3
4
5
6
7
8
9public static void main(String[] args) { String[] strs = {"张三","李四","王五"}; for(String names : strs){ System.out.println(names); } }
2.遍历List
复制代码
1
2
3
4
5
6
7
8
9
10
11
12public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("张三"); list.add("王五"); list.add("李四"); for(String name : list){ System.out.println(name); } }
二.局限性
foreach虽然能遍历数组或者集合,但是只能用来遍历,无法在遍历过程中对数组或者集合进行修改,而for循环可以在遍历的过程中对原数组或者集合进行修改
1.数组
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public static void main(String[] args) { String[] strs = {"张三","李四","王五"}; //foreach for(String names : strs){ names = "改改"; } System.out.println("foreach:"+Arrays.toString(strs)); //for for(int i=0; i<strs.length; i++){ strs[i] = "改改"; } System.out.println("for:"+Arrays.toString(strs));
2.集合
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("张三"); list.add("王五"); list.add("李四"); for(String name : list){ name = "改改"; } System.out.println("foreach_list:"+Arrays.toString(list.toArray())); for(int i=0; i<list.size(); i++){ list.set(i, "改改"); } System.out.println("for_list:"+Arrays.toString(list.toArray())); }
最后
以上就是任性小刺猬最近收集整理的关于Java--foreach循环的全部内容,更多相关Java--foreach循环内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复