当我试图删除单个项目时,此方法工作良好,但当我使用文件删除多个项目时,我得到并发修改异常。
static void delete(String dString) {
LinkedList<String> AddressBook2 = AddressBook;
for(String s : AddressBook2){
String subString = dString.toUpperCase().substring(7);
if(s.toUpperCase().contains(subString)){
AddressBook.remove(s);
System.out.println("Removal Successful: "+ s);
}
}
System.out.println("ERROR: Not found for Removal: "+dString.substring(7));
System.out.println("----------------------------");
}
可以使用迭代器安全地删除元素,如:
String subString = dString.toUpperCase().substring(7);
boolean resultFound = false;
for (Iterator<String> iterator = addressBook2.iterator(); iterator.hasNext();) {
String s = iterator.next();
if(s.toUpperCase().contains(subString)) {
iterator.remove();
System.out.println("Removal Successful: "+ s);
resultFound = true;
}
}
if (!resultFound) {
System.out.println("ERROR: Not found for Removal: "+dString.substring(7));
}
System.out.println("----------------------------");
还有,你不需要在每次循环迭代中都得到substring,所以我把它移出了for语句。您必须提供一些逻辑,使您的消息ERROR: Not found for Removal:
只在没有真正找到的情况下发生。我用布尔标志作为例子