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