简体   繁体   English

如何在没有concurrentmodificationexception的for循环中向java中的arraylist添加元素

[英]How to add elements to an arraylist in java inside a for loop without concurrentmodificationexception

I have a Java Spring MVC Web application. 我有一个Java Spring MVC Web应用程序。 I am trying to iterate through an ArrayList and add new elements to the list based on certain conditions. 我试图迭代一个ArrayList并根据某些条件将新元素添加到列表中。 I use the following code: 我使用以下代码:

List<LocationHourListHB> locationHoursList = new ArrayList<LocationHourListHB>();
List<HoursTO> hourList = listHoursByEntityId(applicationId, siteId, locationId);
for (HoursTO hoursTO : hourList) 
{
    if(locationHoursList.size() == 0)
    {
        LocationHourListHB locationHourListHB = new LocationHourListHB();
        locationHourListHB.setStartTIme(hoursTO.getStartTime());
        locationHourListHB.setEndTime(hoursTO.getEndTime());
        locationHoursList.add(locationHourListHB);
        break;
    }
    for (LocationHourListHB locationHour : locationHoursList) 
    {
        if(hoursTO.getStartTime().equalsIgnoreCase(locationHour.getStartTIme()) && hoursTO.getEndTime().equalsIgnoreCase(locationHour.getEndTime()))
        {
            break;
        }
        else
        {
            LocationHourListHB locationHourListHB = new LocationHourListHB();
            locationHourListHB.setStartTIme(hoursTO.getStartTime());
            locationHourListHB.setEndTime(hoursTO.getEndTime());
            locationHoursList.add(locationHourListHB);
        }
    }
}
}

But executing this throws a concurrent modification exception . 但执行此操作会引发concurrent modification exception I have done some research and found that it can be solved using an iterator or list iterator . 我做了一些研究,发现它可以使用iteratorlist iterator来解决。 Is there a good example to follow for using the list iterator to solve my issue. 是否有一个很好的例子可以使用list iterator来解决我的问题。 Or is there any better solution that could save me. 或者有没有更好的解决方案可以拯救我。

I have tried the following code: 我试过以下代码:

for (HoursTO hoursTO : hourList) 
{
    if(locationHoursList.size() == 0)
    {
        LocationHourListHB locationHourListHB = new LocationHourListHB();
        locationHourListHB.setStartTIme(hoursTO.getStartTime());
        locationHourListHB.setEndTime(hoursTO.getEndTime());
        locationHoursList.add(locationHourListHB);
        }
        ListIterator<LocationHourListHB> iter = locationHoursList.listIterator();
        while(iter.hasNext())
        {
        if(!(iter.next().getStartTIme().equalsIgnoreCase(hoursTO.getStartTime()) && iter.next().getEndTime().equalsIgnoreCase(hoursTO.getEndTime())))
        {
            LocationHourListHB locationHourListHB = new LocationHourListHB();
            locationHourListHB.setStartTIme(hoursTO.getStartTime());
            locationHourListHB.setEndTime(hoursTO.getEndTime());
            iter.add(locationHourListHB);
        }
    }
}

But getting a NoSuchElementException 但是获得NoSuchElementException

You can use ListIterator like this: 您可以像这样使用ListIterator:

ArrayList<LocationHourListHB> locationHoursList = new ArrayList<LocationHourListHB>();

ListIterator<LocationHourListHB> iterator = locationHoursList.listIterator();

while(iterator.hasNext(){
LocationHourListHB locationHour = iterator.next()
  if(hoursTO.getStartTime().equalsIgnoreCase(locationHour.getStartTIme()) && hoursTO.getEndTime().equalsIgnoreCase(locationHour.getEndTime()))
        {
            break;
        }
        else
        {
            LocationHourListHB locationHourListHB = new LocationHourListHB();
            locationHourListHB.setStartTIme(hoursTO.getStartTime());
            locationHourListHB.setEndTime(hoursTO.getEndTime());
            iterator.add(locationHourListHB);
        }

}

@Geo Thomas I see you were trying to edit the answer, for this is better to write into comments or update your own question. @Geo Thomas我看到你正在尝试编辑答案,因为最好写入评论或更新你自己的问题。 The problem with the code you send into edit is that you are calling iterator.next() mutltiplle times after iterator.hasNext(). 您发送到编辑的代码的问题是您在iterator.hasNext()之后调用iterator.next()mutltiplle次。 Every time you call iterator.next() it will return the next element in the list, not the same one! 每次调用iterator.next()时,它都会返回列表中的下一个元素,而不是同一个元素!

you should use it like this: 你应该像这样使用它:

LocationHourListHB locationHour = iterator.next()

ANd then use in the code locationHour. 然后在代码locationHour中使用。

You can't use iterator, you'll get the same exception if you try to add to the list while iterating, and there's no add method on the iterator. 您不能使用迭代器,如果您在迭代时尝试添加到列表中,则会得到相同的异常,并且迭代器上没有添加方法。

ListIterator has an add method which adds the new item before the next one. ListIterator有一个add方法,可以在下一个方法之前添加新项。

    List<String> list = new ArrayList<>();
    list.add("one");
    list.add("two");
    ListIterator<String> iterator = list.listIterator();
    while (iterator.hasNext()) {
        String value = iterator.next();
        if (value.equals("one")) {
            iterator.add("three");
        }
    }
    System.out.println(list);  // prints [one, three, two]

If you need to add to the end of the list, use a second list and add them after the loop 如果需要添加到列表的末尾,请使用第二个列表并在循环后添加它们

    List<String> list = new ArrayList<>();
    List<String> newValues = new ArrayList<>();
    list.add("one");
    list.add("two");
    for (String value : list) {
        if (value.equals("one")) {
            newValues.add("three");
        }
    }
    list.addAll(newValues);
    System.out.println(list);  // prints [one, two, three]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 添加 ArrayList 元素时如何避免“ConcurrentModificationException”? - How to avoid "ConcurrentModificationException" while add ArrayList elements? Java在没有ConcurrentModificationException的情况下在同一循环中添加/删除 - Java add/remove at the same loop without ConcurrentModificationException 迭代并从 ArrayList 中删除元素时如何避免 java.util.ConcurrentModificationException - How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList 如果某个元素存在于另一个元素中,则从Arraylist中删除它们,而不会引发ConcurrentModificationException - Remove elements from an Arraylist if they are present in another one without raising ConcurrentModificationException java ArrayList中的ConcurrentModificationException - ConcurrentModificationException in java ArrayList java.util.ArrayList通过循环中的其余元素循环 - java.util.ArrayList loop through rest elements inside a loop Java ConcurrentModificationException; 单线程; 没有为每个循环 - Java ConcurrentModificationException; single Thread; without for each loop 如果我们在迭代时最后在ArrayList中添加元素,则抛出ConcurrentModificationException - Throwing ConcurrentModificationException if we add elements in ArrayList at the end while iterating Java:添加元素 ArrayList - Java: Add elements ArrayList 如何在Java中使用ArrayList添加元素? - How to add elements using ArrayList in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM