[英]How to remove() a sequence of String elements in an ArrayList() using indices in java?
[英]How to remove elements in ArrayList through for loop using Java
我一直在尝试使用remove()
对象remove()
ArrayList
中的一个元素,但它仍然没有删除任何内容。 我已经检查了存储在我的数组中的列表,一切都显示正常,但是当我尝试删除一个元素时,它不起作用。 我的目标是用户输入要删除的名称,然后搜索与该名称相同的列表并将其删除。 List Array 设置为全局。
这是代码:
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));
假设您有带有学生姓名的字符串 ArrayList,其大小为 5。每当您找到要删除的字符串时,在 for 循环的下一次迭代中,您将跳过一个 ArrayList 元素。 您可以通过减少 for 循环迭代器来克服这个问题,这是一个可行的解决方案,但不是最好的。 如果您的循环在第三个元素 (fullName.get(2)) 上并且它符合您的删除条件,您将删除它,现在有一个包含 4 个元素的 ArrayList,而不是 5 个,在下一次迭代中 (fileName.get(3))您实际上将跳过一个已转移到已删除元素位置的 ArrayList 元素(整个 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);
x--;
}
}
}
这应该可行,但正如上面有人评论的那样,使用 Iterator 将是更好的解决方案。
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();
// collecting the objects that we want to delete
List<String> foundList = new ArrayList<String>();
for(int x = 0; x < fullName.size();x++){
if(fullName.get(x).equalsIgnoreCase(removeName)){
foundList.add(fullName.get(x));
}
}
// delete objects
fullName.removeAll(foundList);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.