进阶day02-增强for循环遍历数组和集合
This commit is contained in:
61
javaSE-day02/src/com/inmind/foreach03/ForEachDemo03.java
Normal file
61
javaSE-day02/src/com/inmind/foreach03/ForEachDemo03.java
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package com.inmind.foreach03;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
/*
|
||||||
|
6.增强for循环遍历数组
|
||||||
|
|
||||||
|
由于部分集合没有索引,在jdk1.5出现了一个遍历容器的增强for循环的格式,作用就是能够简化迭代器代码
|
||||||
|
|
||||||
|
foreach循环的格式:
|
||||||
|
for(数据类型 变量名: 容器){
|
||||||
|
循环体
|
||||||
|
}
|
||||||
|
|
||||||
|
格式中:
|
||||||
|
数据类型:容器中存放的数据类型
|
||||||
|
变量名:就是一个标识符,表示容器中的每个元素
|
||||||
|
容器:就是数组和集合
|
||||||
|
循环体:就是java代码
|
||||||
|
|
||||||
|
使用场景:
|
||||||
|
1.如果要索引,就使用普通for循环
|
||||||
|
2.如果不要索引,就可以使用增强for循环
|
||||||
|
|
||||||
|
foreach循环其实是一个语法糖,本质不变,但是代码简化.这让程序员像吃了糖一样甜蜜
|
||||||
|
|
||||||
|
数组的foreach循环本质是普通for循环.
|
||||||
|
集合的foreach循环本质是迭代器iterator.
|
||||||
|
|
||||||
|
*/
|
||||||
|
public class ForEachDemo03 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int[] arr = {1, 2, 3};
|
||||||
|
//普通for循环,可以操作索引
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
System.out.println(arr[i]);
|
||||||
|
System.out.println(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
System.out.println("-------------------------------");
|
||||||
|
//数组的增强for循环,也叫foreach循环
|
||||||
|
int index = 0;//自定义索引
|
||||||
|
for(int temp : arr){
|
||||||
|
System.out.println(index++);
|
||||||
|
//循环操作容器中的每个元素
|
||||||
|
System.out.println(temp);
|
||||||
|
}
|
||||||
|
System.out.println("----------------------");
|
||||||
|
Collection<String> lists = new ArrayList<>();
|
||||||
|
lists.add("刘备");
|
||||||
|
lists.add("关羽");
|
||||||
|
lists.add("张飞");
|
||||||
|
for (String str : lists) {
|
||||||
|
System.out.println(str);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,9 +29,6 @@ public class IteratorDemo02 {
|
|||||||
lists.add("刘备");
|
lists.add("刘备");
|
||||||
lists.add("关羽");
|
lists.add("关羽");
|
||||||
lists.add("张飞");
|
lists.add("张飞");
|
||||||
lists.add("张飞");
|
|
||||||
lists.add("张飞");
|
|
||||||
lists.add("张飞");
|
|
||||||
|
|
||||||
//由于当前单列集合没有索引api,只能通过通用性更强的迭代器来遍历
|
//由于当前单列集合没有索引api,只能通过通用性更强的迭代器来遍历
|
||||||
Iterator<String> iterator = lists.iterator();
|
Iterator<String> iterator = lists.iterator();
|
||||||
|
|||||||
Reference in New Issue
Block a user