当前案例用于演示制造异常 - 这个异常在以后的操作中可能会出现:
使用集合的存储多个对象的时候,假设当遇到16岁的人时,就添加一个90岁的人
该案例中,可能会出现并发修改异常,迭代器所认为的集合状态和集合真正的状态不统一,所以就报错了!
package Test17_Demo.Demo06;/*@create 2020--12--07--14:33*/public class Person {private String name;private int age;public Person() {}public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}}
制造异常:
package Test17_Demo.Demo06;/*@create 2020--12--07--14:57*/import Test17_Demo.Demo06.Person;import java.util.ArrayList;import java.util.Iterator;public class CurrentModificationDemo {public static void main(String[] args) {//创建对象ArrayList<Person> arrayList = new ArrayList<>();//添加对象arrayList.add(new Person("jack",18));arrayList.add(new Person("rose",16));arrayList.add(new Person("Aobama",60));arrayList.add(new Person("Lucy",25));arrayList.add(new Person("Tom",30));arrayList.add(new Person("sanfeng.zhang",90));//调用迭代器Iterator<Person> iterator = arrayList.iterator();while (iterator.hasNext()) {Person p = iterator.next();System.out.println(p.getAge() + "岁的" + p.getName());//判断年龄是不是为16if (p.getAge() == 16) {//存在则添加90岁的人arrayList.add(new Person("三丰",90));}}}}
解决异常:
package Test17_Demo.Demo06;/*@create 2020--12--07--14:57*///解决方案import java.util.ArrayList;import java.util.Iterator;public class CurrentModificationDemo02 {public static void main(String[] args) {//创建对象ArrayList<Person> arrayList = new ArrayList<>();//添加对象arrayList.add(new Person("jack",18));arrayList.add(new Person("rose",16));arrayList.add(new Person("Aobama",60));arrayList.add(new Person("Lucy",25));arrayList.add(new Person("Tom",30));//调用迭代器Iterator<Person> iterator1 = arrayList.iterator();while (iterator1.hasNext()) {Person p = iterator1.next();//System.out.println(p.getAge() + "岁的" + p.getName());//判断年龄是不是为16if (p.getAge() == 16) {//存在则添加90岁的人arrayList.add(new Person("三丰",90));//当遇到16岁的人的时候,就退出当前的操作break;}}//曲线救国 - 重新迭代集合中的数据 - 重新获取迭代器Iterator<Person> iterator2 = arrayList.iterator();while (iterator2.hasNext()) {Person p = iterator2.next();System.out.println(p.getAge() + "岁的" + p.getName());}}}
