Reputation: 33
In my project of creating contacts and managing them, when i remove an object from an Array List in a for-loop, a Concurrent Modification Exception is being thrown(as mentioned in javadoc).
My question is how can i remove the object without getting "Concurrent Modification Exception"
I looked at similar posts but couldn't find the answer, some had complex code and many asked why a exception i s not thrown. This question didn't help me/this specific problem You can read the above link an help me out too(I'm rather new)
I am using jdk 14, ide:intelliJ,
I have created methods to manage contacts and get input but I'm only providing the method in which the exception is thrown.
public class Main {
private static ArrayList<Contact> contacts;
contacts = new ArrayList<>();
private static void deleteContact() {
System.out.println("Please enter contact name: ");
String name = scanner.next();
if (name.equals("")){
System.out.println("Please enter the name");
deleteContact();
}else{
boolean doesExist = false;
for(Contact c:contacts) { //Error pointed on this line.
if (c.getName().equals(name)) {
doesExist = true;
contacts.remove(c);
}
}
if (!doesExist){
System.out.println("There is no such contact");
}
}
showInitialOptions();
}
}
Important code from class 'Contact'
public class Contact {
private String name;
private int number;
private String email;
public Contact(String name, int number, String email ) {
this.name = name;
this.number = number;
this.email = email;
;
}
public String getName() {
return name;
}
}
Upvotes: 0
Views: 229
Reputation: 140
You can use an Iterator
to iterate over the ArrayList
:
Iterator<Contact> it = contacts.iterator();
while(it.hasNext()){
Contact c = it.next();
if(c.getName().equals(name)){
doesExist = true;
it.remove();
}
}
Upvotes: 2
Reputation: 102
For your particular problem, Change the line from
for(Contact c:contacts) {
To
for(int i=contacts.size()-1; i>-1; i--) {
It should work
Upvotes: 1