我正在管理一个小的学生名册的项目。所需的功能之一是能够使用学生ID标识符删除学生的记录,并且如果学生ID不存在,则该删除功能会产生错误。
此删除验证所需的测试是删除同一学生ID两次,然后查看是否在第二次调用remove方法时显示错误消息。
第一个remove方法调用正在运行,并且已成功删除了所调用学生ID的元素。但是,第二个删除是给我一个并发修改异常错误。
下面的代码创建Student数组列表并调用remove方法(两次)。
static ArrayList<Student> myRoster = new ArrayList<>();
public static void main(String[] args)
{
// add students to the roster
add("1", "John", "Smith", "John1989@gmail.com", "20",
88, 79, 59);
add("2", "Suzan", "Erickson", "Erickson_1990@gmail.com", "19",
91, 72, 85);
add("3", "Jack", "Napoli", "The_lawyer99yahoo.com", "19",
85, 84, 87);
add("4", "Erin", "Black", "Erin.black@.com", "22",
91, 98, 82);
//loop through the ArrayList and for each element:
remove("3");
remove("3");
这是删除方法。这是我目前的想法:
*为了首先检查学生证是否存在,我将if / else放入嵌入式if / else循环中以删除该学生。
*我使用contains来查看数组列表是否包含学生ID。如果是,则执行if / else删除。如果没有,它将给出失败的打印输出并返回。
public static void remove(String studentID)
//remove student from roster by student ID
//print error message if student is not found
{
for(Student b: myRoster)
{
String record = b.getStudentID();
Boolean a = studentID.contains(studentID);
if (a)
{
Boolean c = record.matches(studentID);
if (c)
{
myRoster.remove(b);
System.out.println("Student ID " + studentID + " was removed.");
}
else
{
;
}
}
else
{
System.out.println("Student ID does not exist.");
}
这是我得到的错误:
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at Roster.remove(Roster.java:48)
at Roster.main(Roster.java:28)
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at Roster.remove(Roster.java:48)
at Roster.main(Roster.java:28)
有任何想法吗?
最佳答案
使用迭代器迭代列表时,不能安全地修改列表的内容。使用ListIterator执行此操作。
ListIterator<Student> it = myRoster.listIterator();
while (it.hasNext()) {
Student b = it.next();
if (b.getStudentId() == studentId) {
it.remove(); // Removes b from myRoster
}
...
}
请注意,如果有很多学生,这将无法很好地扩展。最好使用
Map<String, Student>
来保存您的花名册,密钥是学生ID。