我编写了自己的类,名为 Person
,其中包含变量 String name
、intage
和 double height
,以及 toString()
。然后,我创建了一个 Person
的 ArrayList
,并添加了几个实例。打印效果很好。现在我想编写一个方法,当我写入名称时,检查 ArrayList 中是否有具有该名称的实例,如果是,则删除该实例。我该怎么做?
这是我写的:
import java.util.*;
public class PersonManager {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<>();
Scanner keyboard = new Scanner(System.in);
people.add(new Person("Adam ", 29, 177.5));
people.add(new Person("Bernadette", 19, 155.2));
people.add(new Person("Carl", 45, 199));
for (Person p : people)
System.out.println(p);
System.out.println("Select person to remove");
String name = keyboard.nextLine();
// if there is a person with that name in the list, that
//person gets removed from the list
}
}
最佳答案
如果您使用 JAVA 8 并且不介意从原始列表创建新列表,您可以像这样使用 JAVA 8 流:
ArrayList<Person> people = new ArrayList<>();
people.add(new Person("Adam ", 29, 177.5));
people.add(new Person("Bernadette", 19, 155.2));
people.add(new Person("Carl", 45, 199));
String nameToRemove = "name";
people = people.stream().filter((t) -> !t.getName().equals(nameToRemove)).collect(Collectors.toList());
关于java - 从 ArrayList 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30359420/