简体   繁体   中英

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

I have a Java Spring MVC Web application. I am trying to iterate through an ArrayList and add new elements to the list based on certain conditions. 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 . I have done some research and found that it can be solved using an iterator or list iterator . Is there a good example to follow for using the list iterator to solve my issue. 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

You can use ListIterator like this:

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. The problem with the code you send into edit is that you are calling iterator.next() mutltiplle times after iterator.hasNext(). Every time you call iterator.next() it will return the next element in the list, not the same one!

you should use it like this:

LocationHourListHB locationHour = iterator.next()

ANd then use in the code 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.

    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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM