簡體   English   中英

ConcurrentModificationException while making.removeAll() 方法

[英]ConcurrentModificationException while making .removeAll() method

我的代碼看起來像這樣

public class ListAnalyzer {
public static List<String> base;

public static void addOfflineToBase(String offline) {
    base.add(offline);
}

public static List<String> prepareArrayList() throws IOException {
    base = Files.readAllLines(Paths.get("/Users/noname/Desktop/test.txt").toAbsolutePath().normalize());
    List<String> part = base.subList(0, 200);
    base.removeAll(part);
    saveBase();
    return part;
}

當我嘗試運行它時 - 我看到:

Unable to evaluate the expression Method threw 'java.util.ConcurrentModificationException' exception.

當我嘗試 base.removeAll(part) 時,我在這里看不到沖突。 有人能幫助我嗎? 順便說一句:saveBase() 只是將數據寫入文本文件 UPD:Stacktrace

21:59:26: Executing task 'App.main() --scan'...

> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE

> Task :App.main() FAILED
2 actionable tasks: 1 executed, 1 up-to-date

Publishing a build scan to scans.gradle.com requires accepting the Gradle Terms of Service defined at https://gradle.com/terms-of-service. Do you accept these terms? [yes, no] Exception in thread "main" java.util.ConcurrentModificationException
 at java.base/java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1445)
 at java.base/java.util.ArrayList$SubList.size(ArrayList.java:1185)
 at java.base/java.util.AbstractCollection.isEmpty(AbstractCollection.java:87)
 at com.lukaspradel.steamapi.webapi.request.GetPlayerSummariesRequest$GetPlayerSummariesRequestBuilder.<init>(GetPlayerSummariesRequest.java:41)
 at hexlet.code.App.getOnlineIds(App.java:39)
 at hexlet.code.App.start(App.java:21)
 at hexlet.code.App.main(App.java:16)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':App.main()'.
> Process 'command '/Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 337ms

```lang-none

我需要了解如何安全地從base中刪除字符串。

有兩種方式:

  1. 添加一些應用程序級鎖定,這樣您就不會在其他內容迭代列表時嘗試從列表中刪除字符串。

  2. 使用並發集合類型而不是List (不清楚哪種集合類型最合適。沒有合適的並發列表類型;即支持高效更新的類型。)並發集合類型在java.util.concurrent package中定義。

我想問題來自這些行:

List<String> part = base.subList(0, 200);
base.removeAll(part);

列表part實際上由列表base支持,因此base的變化反映在part中。 那可能會導致這樣的異常。

為了確認這一點,您能否嘗試:

List<String> part = new ArrayList<>(base.subList(0, 200));
base.removeAll(part);

另一種可能性,它做一些不同的事情,但與你的相似:

 base.subList(0, 200).clear();

這將刪除 0 到 200 范圍內的所有元素,前提是所有元素都是唯一的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM