【Java ListIterator迭代器】

package com.yuzhenc.collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author: yuzhenc
 * @date: 2022-03-09 20:37:14
 * @desc: com.yuzhenc.collection
 * @version: 1.0
 */
public class Test10 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("abc");
        list.add("def");
        list.add("ghi");
        
        for(Iterator<String> iterator = list.iterator(); iterator.hasNext(); ){
            if ("def".equals(iterator.next()))
                //这里进行了并发修改,执行时会报错
                list.add("jkl");
        }
    }
}

【Java ListIterator迭代器】_第1张图片

package com.yuzhenc.collection;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * @author: yuzhenc
 * @date: 2022-03-09 20:44:12
 * @desc: com.yuzhenc.collection
 * @version: 1.0
 */
public class Test11 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("abc");
        list.add("def");
        list.add("ghi");

        for(ListIterator<String> iterator = list.listIterator(); iterator.hasNext(); ){
            if ("def".equals(iterator.next()))
                //这里迭代时,通过迭代器实现了修改
                iterator.add("jkl");
        }
        System.out.println(list);//[abc, def, jkl, ghi]
    }
}

你可能感兴趣的:(JAVA,笔记,java,开发语言,intellij-idea)