List移除元素的问题

0.096字数 58阅读 16

问题描述

package com.startsi.bjairport.listen;

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

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("苹果");
        list.add("香蕉");
        list.add("车厘子");
        String fruits = "车厘子";
        if (null != list && list.size() > 0) {
            for (String fruit : list) {
                if (fruits.equals(fruit)) {
                    list.remove(fruit);
                }
                System.out.println(fruit);
            }

        }
        
    }
}

异常信息

苹果
香蕉
Exception in thread "main" 车厘子
java.util.ConcurrentModificationException
at java.util.ArrayList _Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList_Itr.next(ArrayList.java:851)
at com.startsi.bjairport.listen.Test.main(Test.java:14)

解决方式

package com.startsi.bjairport.listen;

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

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("苹果");
        list.add("香蕉");
        list.add("车厘子");
        String fruits = "车厘子";
        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (fruits.equals(list.get(i))) {
                    list.remove(list.get(i));
                    i--;//索引-1
                }
                System.out.println(list.get(i));
            }
            
        }
        
    }
}

关键点

if (fruits.equals(list.get(i))) {
      list.remove(list.get(i));
      i--;//索引-1
}

推荐阅读更多精彩内容