231 增强for循环
增强型for语句,有时称为for-each-loop语句
增强for循环的目的,简化数组和Collection集合的遍历
- 实现Iterator接口的类允许其对象成为增强型for语句的目标
- 出现于JDK5后,内部原理是一个Iterator迭代器
> 来自帮助文档,public interface Iterable<T>,实现此接口允许对象成为增强型for语句的目标
> Collection体系的集合都可以成为增强型for语句的目标
【增强for的格式】
for(元素数据类型 变量名:数组名或Collection集合名){
//在此处使用变量即可,该变量就是元素;
}
---
int[] arr = {1,2,3,4,5};
for(int i:arr){
sout(i)
}
--------------------------------------------------------------
Set<String> jianjihe = ha.keySet();
for (String jian : jianjihe){
System.out.println(jian+":");
ArrayList<String> zhijihe = ha.get(jian);
for (String zhi : zhijihe){
System.out.println("\t"+zhi);
}
}
--------------------------------------------------------------
package e231;
import java.util.ArrayList;
import java.util.List;
// show1: create an int-array,,,output it by for-each-loop,,,run it...
// show2: create another String-array,,,output it by for-each-loop,,,run it...
// show3: create another Collection-array,,,output it by for-each-loop,,,run it...
// 通过是否抛出并发修改异常,验证Iterator的内部原理是迭代器
public class ForEachLoopDemo {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
System.out.println("6.output the int-array by for-each-loop");
for (int i:arr){
System.out.println("\t"+i);
}
System.out.println("13.output the String-array by for-each-loop");
String[] sa = {"231","hello","world"};
for (String i:sa){
System.out.println("\t"+sa);
}
System.out.println("23.output the Collection-array by for-each-loop");
List<String> list = new ArrayList<String>();
list.add("TRACY");
list.add("JIMMY");
list.add("BEN");
for (String s:list){
System.out.println("\t"+s);
}
for (String s:list){
if (s.equals("TRACY")){
list.add("JAVA");//ConcurrentModificationException
}
}
}
}