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

Creating Objects According to an Input File
Regex : How to avoid matching a word in a string upon a condition
Unit testing Exception scenarios with cucumber in java
How to get Jackson to ignore minimal fields for a certain view?
Hibernate Restrictions subquery with id of main query
Unable to get entityManager.getCriteriaBuilder in jpa with eclipselink
Hazelcast 3.8-EA WARNING:Received data format is invalid issue
How to bind a progressbar to a task?
how to set alarm scheduling with notification in android?
import excel file to java. Need file (not content)
OpenGL support broken after updating GPU drivers
ListView shows only one item
Objectify queries: setting limit above 300 does not work
Maven generated static metamodels in Hibernate 5.2 not recognized by DAO classes
Calling an Object parameter ArrayList and converting it to a String in CSV format
How to display AlertDialog with ImageView and EditText without layout.xml?

Categories

HOME
maven
ms-access
debugging
magnific-popup
reflection
relayjs
electron
webstorm
youtube-dl
getelementsbytagname
ckeditor
networkx
autotools
node-notifier
slurm
numeral.js
rascal
jplayer
clearcase-ucm
clojurescript
jprofiler
one-hot-encoding
intentfilter
core-text
numerical-methods
selectedindexchanged
wpfdatagrid
buck
webkitspeechrecognition
c++-amp
quote
google-cloud-nl
r-raster
phonegap
galsim
semantic-versioning
data-manipulation
caret
cloud-code
android-ble
vxworks
ansible-playbook
elmah
janrain
node-gyp
s
businessworks
flickr-api
rainbowtable
smartcontracts
komodoedit
sqlclient
crypt
dtexec
sqldf
vtigercrm
cubes
httplistener
infix-notation
elements
xml-attribute
paypal-express
websitepanel
jwplayer7
packagist
bluegiga
iad
quicklisp
sankey-diagram
apache-commons-fileupload
createprocessasuser
streambase
javax.mail
csquery
c3
googlemock
onactivityresult
typeof
fluentautomation
jquery-layout
mechanize-ruby
braille
concurrent-collections
srs
terminal-services
pyhdf
web2py-modules
blending
soundtouch
flash-builder4.5
back-stack
kyotocabinet
angularjs-controller
itmstransporter
venn-diagram
javaspaces
newtonscript
subscript
gnustep
hirefire
appendto
gdlib
web-architecture
text-coloring

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