Traverse the array to delete elements, causing the length of the array to change, the solution

When the array is traversed and added or deleted, the size of the array is changed. Here is the solution:

public static void main(String[] args) {
    
    
        ArrayList <String>list=new ArrayList<>();
        for(int i=0;i<5;i++){
    
    
            list.add("aa"+i);
        }
        for (String s : list) {
    
    
            System.out.println(s);
        }
        System.out.println("修改后的列表");
        for (int i=0;i<list.size();i++){
    
    
            String s=list.get(i);
            if(s.indexOf("aa3")!=-1){
    
    
                list.remove(s);
            }
        }
        System.out.println(list);

    }

Guess you like

Origin blog.csdn.net/zhanlong11/article/details/109644857