gpt4 book ai didi

java - 传递 arraylist 的副本以避免并发修改异常

转载 作者:行者123 更新时间:2023-11-30 07:12:55 25 4
gpt4 key购买 nike

我有下面的java代码,它抛出ConcurrentModificationException下面是java代码

下面是正在声明的列表

List<BrokerInvoiceLineItem> brokerInvoiceLineItems= new ArrayList<BrokerInvoiceLineItem>();
brokerInvoiceLineItems=brokerInvoice.getLineItems();

下面是抛出并发修改异常的代码

if (brokerInvoiceLineItems == null) {
brokerInvoiceLineItems = brokerInvoiceHome.findLineitemsByInvoiceId(brokerInvoice.getId());
}
for (BrokerInvoiceLineItem brokerInvoiceLineItem : brokerInvoiceLineItems) {
if (fetchNewAndOldCFandAmend(brokerInvoiceLineItem)) {
if (!isAnyValid)
isAnyValid = true;
}
}

现在的问题是,如果brokerInvoiceLineItems不为空,那么对于第一次迭代,它会进入循环,并且名为isAnyValid的变量的值设置为true,但是一旦第一次迭代结束,那么对于第二次迭代,它会再次进入line for (BrokerInvoiceLineItembrokerInvoiceLineItem :brokerInvoiceLineItems){ 然后它不会进入下一行,它会抛出并发修改异常

所以这意味着它必须在迭代时修改brokerInvoiceLineItems 的大小。这可能发生在 fetchNewAndOldCFandAmend 中,因此我正在考虑制作 BrokerInvoiceLineItems 的副本并修改该副本。所以请告知我如何将副本传递给 fetchNewAndOldCFandAmend(brokerInvoiceLineItem)

还请告知如何使用 copyonwriteArray list 来避免此类错误

最佳答案

我认为当您删除 brokerInvoiceLineItems 的某些项目时,您会遇到此异常。

要避免此异常,请使用迭代器

Iterator<BrokerInvoiceLineItem> iterator = brokerInvoiceLineItems.iterator();
while(iterator.hasNext()) {
BrokerInvoiceLineItem brokerInvoiceLineItem = iterator.next();
// your code
}

而不是

for (BrokerInvoiceLineItembrokerInvoiceLineItem:brokerInvoiceLineItems) {

所以你的代码是:

Iterator<BrokerInvoiceLineItem> iterator = brokerInvoiceLineItems.iterator();
while(iterator.hasNext()) {
BrokerInvoiceLineItem brokerInvoiceLineItem = iterator.next();
if (fetchNewAndOldCFandAmend(brokerInvoiceLineItem)) {
if (!isAnyValid)
isAnyValid = true;
}
}

关于java - 传递 arraylist 的副本以避免并发修改异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38894059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com