java


How to fix ConcurrentModificationException when using foreach to iterate over a List? [duplicate]


This question already has an answer here:
Java - adding elements to list while iterating over it
5 answers
am trying to add objects to an arraylist after verifying either that object already exits in the list or not. But am getting a ConcurrentModificationException and I don't know how to fix it.
Any help?
here is the code that throws the exception:
List<ContexteNb> projets = service.findByprojet(p);
List<ProjetVTO> models = new ArrayList<>();
for (ContexteNb contexteNb : projets) {
ProjetVTO model = new ProjetVTO();
model.setNbillets(contexteNb.getNbBillet());
model.setAnnee(contexteNb.getDimDate().getAnnee());
model.setPriorite(contexteNb.getDimPriorite().getPriorite());
if (models.isEmpty()) {
models.add(model);
}
else{
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee())
&& (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
} else {
models.add(model);
}}}}
thanks,
The exception results from adding an element to the models List while iterating over it.
You have to change your logic. I suspect the logic of your inner loop is wrong anyway, and fixing it will also solve your problem. You probably want to search first if the List contains any element matching model and modify it if found, and only add a new instance to the List if you don't find a match (i.e. after the loop is over).
Your inner loop would look like this:
if (models.isEmpty()) {
models.add(model);
} else {
boolean found = false;
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
found = true;
break;
}
}
if (!found) {
models.add(model);
}
}
or simply (you can eliminate the outer condition):
boolean found = false;
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
found = true;
break;
}
}
if (!found) {
models.add(model);
}

Related Links

Input Hashmap<Object, Object> Into JSONObject
Error: Could not find or load main class using external libraries
Java - requestFocus on current Element
Multicast : using joinGroup on a multicast socket (java/android) packet isn't received
Converting JSON ZonedDateTime POJO
Handling Retry Logic on HttpResponse 404 with Akka http
Write stack trace to Extent Reports from the #afterMethod in TestNG
Draw many pixel points android canvas or opengl?
Working with fetched objects is too slow [duplicate]
Jhipster Liquibase Modified Entity via Entity Manager but DB not modified
How is a generic list type erased? When I try it myself, it gives an error
Screen goes blank and app force closes itself [closed]
Palindrome parser logic error
Getting error in client-server programming
Parsing Soap Service use of Retrofit I am facing exception like this(i.e)mismatched body model in the class envelope model in the response
How to get a spring bean in a bean-defining method

Categories

HOME
variables
atom-editor
webpack
fluentd
path-finding
jira
filtering
yarn
microservices
packages
installshield
datastax-java-driver
portia
windows-10-universal
vifm
volttron
modx-revolution
task
circuit
dynamics-crm-online
fatal-error
firefox-webextensions
nas
swiftlint
kryo
errorlevel
csrf-protection
dcevm
rundeck
javacv
pepper
spark-jobserver
tooltipster
rst2pdf
assistant
replaceall
bpel
bcd
nameservers
kendo-ui-grid
azure-sql-database
form-data
sequential
devextreme
occlusion
c11
ssjs
android-fingerprint-api
temporary-files
ws-security
sfdc
grid.mvc
texmaker
powershell-dsc
janrain
android-mediaprojection
google-datalayer
jedis
python-c-api
logparser
dropbox-php
dotnetzip
idisposable
snmptrapd
cudafy.net
flutterwave
smart-table
angular-cache
heidisql
gridpane
vmware-tools
disque
persist
suffix-tree
goose
xpath-1.0
intel-fortran
spidermonkey
wyam
myo
javax.mail
facebook-graph-api-v2.4
website-monitoring
mdt
id3v2
php-5.4
funcunit
jquery-layout
dealloc
cloud-connect
pyhdf
spring-io
easy-install
chronoforms
ember-app-kit
html-editor
pvrtc
nsnetservice
bluepill
multipage
javaspaces
subscript
nsdatecomponents
eclipse-templates
data-loss
yetanotherforum
calling-convention
cxxtest
web-application-design
gamequery
infrastructure
revisions
dbal
eqatec
lzh

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App