我一直在尝试使用 remove()
对象删除 ArrayList
中的元素,但它仍然没有删除任何内容。我已经检查了数组中存储的列表,一切都显示正常,但是当我尝试删除一个元素时,它不起作用。我的目标是用户输入要删除的名称,它将搜索与该名称相同的列表并将其删除。列表数组设置为全局。
这是代码:
public static void removeStudents() {
String removeName;
System.out.println("******REMOVE STUDENTS******");
System.out.print("Enter name you wish to remove: ");
removeName = hold.nextLine();
hold.nextLine();
for (int x = 0; x < fullName.size(); x++) {
if (fullName.get(x).equalsIgnoreCase(removeName)) {
fullName.remove(x);
}
}
}
最佳答案
从Java 8开始,有
Collection.removeIf(Predicate<? super E> filter)
您可以轻松地从 List
中删除符合指定条件的元素。 ,但是您不应该在迭代该列表时执行此操作,因为它的索引会发生变化,这可能会导致 ConcurrentModificationException
正如您的问题下面的评论之一中已经提到的。
这样做:
public static void main(String[] args) {
// provide sample data
List<String> students = new ArrayList<>();
students.add("Student 01");
students.add("Student 02");
students.add("Student 03");
students.add("Student 04");
students.add("Student 05");
students.add("Student 06");
// print the list once before any operation
System.out.println("Before:\t" + String.join(", ", students));
// remove elements matching certain criteria, here equality to "Student 03"
students.removeIf(student -> student.equalsIgnoreCase("Student 03"));
// print the list after removal of "Student 03"
System.out.println("After:\t" + String.join(", ", students));
}
输出为
Before: Student 01, Student 02, Student 03, Student 04, Student 05, Student 06
After: Student 01, Student 02, Student 04, Student 05, Student 06
请注意,此示例仅使用 List<String>
,如果您有 List<Student>
,您可以指定删除标准,例如
students.removeIf(student -> student.getName().equalsIgnoreCase(removeName));
关于java - 如何使用Java通过for循环删除ArrayList中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59288375/