【问题标题】:Removing element in ArrayList using INDEX causing java.util.ConcurrentModificationException使用 INDEX 删除 ArrayList 中的元素导致 java.util.ConcurrentModificationException
【发布时间】:2017-02-04 15:16:44
【问题描述】:

以下代码导致

java.util.ConcurrentModificationException

我不知道如何解决这个错误请帮忙!

ArrayList strList =  new ArrayList<String>(Arrays.asList(cmd.split(" ")));

        if (strList.get(0).equals("LIST")) {

        }

        if (strList.get(0).equals("DEPEND")) {
            strList.remove(0); // getting error at this point 
            cm.createComponent(strList);

        }

Full Method外层循环与List无关

public static void main(String[] args) throws IOException {
        ComponentManager cm = new ComponentManager();

    List<String> lines = Files.readAllLines(Paths.get("cmdList.txt"));
    for (String cmd : lines) {
        ArrayList strList =  new ArrayList<String>(Arrays.asList(cmd.split(" ")));

        if (strList.get(0).equals("LIST")) {

        }

        if (strList.get(0).equals("DEPEND")) {
            strList.remove(0);
            cm.createComponent(strList);

        }

        if (strList.get(0).equals("INSTALL")) {

        }

        if (strList.get(0).equals("REMOVE")) {

        }

    }

}

【问题讨论】:

  • 你需要用户迭代器,
  • 这里没有迭代。
  • 尝试通过迭代器删除第一个元素
  • 你能告诉我们完整的堆栈跟踪吗?好像还有另一个问题。
  • @JimGarrison 但是由于列表包含在ArrayList 中,所以OP 也不应该看到UnsupportedOperationException。绝对是问题中缺少细节的情况。

标签: java arraylist


【解决方案1】:

您可以创建一个不同的 ArrayList 并在那里执行删除操作,或者在 arrayList 上放置一个迭代器并使用迭代器删除。

为您的问题找到几个可能的解决方案herehere

【讨论】:

    猜你喜欢
    • 2015-06-15
    • 2011-12-27
    • 1970-01-01
    • 2013-02-24
    • 2013-08-26
    • 1970-01-01
    相关资源
    最近更新 更多