【发布时间】:2015-08-02 06:37:30
【问题描述】:
我用变量String name、int age 和double height 以及toString() 编写了自己的类Person。然后我创建了Persons 的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
}
}
【问题讨论】:
-
你觉得应该怎么做?
-
看起来你已经知道如何循环遍历一个
ArrayList.了关于比较两个String对象你知道什么? -
看看
ArrayList的方法,看看add的反面可能是什么,试一试。如果它不起作用,请展示您的尝试,我们可以提供帮助。
标签: java methods arraylist instance