Reputation: 97
public void searchOwner(List<Appointments> appts, String owner) {
Appointments theOne = null;
for (Appointments temp : appts) {
if (owner.equalsIgnoreCase(temp.owner.name)) {
System.out.println(temp.data);
temp.setResolved(true);
}
}
}
public void checkRemoval() {
for (Appointments appts : appointments) {
if (appts.resolved == true) {
appointments.remove(appts);
}
//Iterator method used before enhanced for-loop
public void checkRemovalI(){
Iterator<Appointments> it = appointments.iterator();
while(it.hasNext()){
if(it.next().resolved = true){
it.remove();
}
}
}
So far this is where I am encountering my problem. I am trying to check the arrayList of Appointments and see if the field (resolved) is set to true, however I am receiving an ConcurrentModification exception during the searchOwner method when trying to set resolved = to true. I've tried using an Iterator in checkRemoval instead of an enhanced for-loop however that didn't help either. I really only need to get the part where the appointment is set to true to work, the checkRemoval seemed to be working early before implementing the changing of the boolean resolved. Any help will be greatly appreciated, thank you.
Upvotes: 0
Views: 35
Reputation: 32680
I'm willing to bet that the ConcurrentModificationException
is not being caused where you say it is, but rather in checkRemoval()
, which you're probably calling before the line you mention where you set resolved
to true, hence your confusion.
I only say this because:
for (Appointments appts : appointments) {
if (appts.resolved == true) {
appointments.remove(appts);
}
}
is a blatant concurrent modification. You cannot remove elements from a collection while you are iterating through it in a loop. Instead, you need to use an iterator:
public void checkRemoval() {
Iterator<Appointment> apptsIterator = appointments.iterator();
while (apptsIterator.hasNext()){
if (appts.next().resolved == true)
apptsIterator.remove(); //removes the last element you got via next()
}
Upvotes: 1
Reputation: 420
The ConcurrentModification exception is thrown, using the for loop, where the Collection gets modified. So the issue need not be the code that you haave posted. You might be having a loop over the appts List, which is calling this function. Posting more of your code might help.
Upvotes: 1