java - 如何编写一个删除方法来从数组列表中删除对象

标签 java arraylist

我正在尝试用java编写一个程序,您可以添加人们的生日、姓名、出生月份和出生年份。我很难想出从数组列表中删除对象的代码,下面是代码。我该如何编写removePerson方法?

import java.util.ArrayList;

public class Analyzer {
    // instance variables - replace the example below with your own
    private final static int DAYS_PER_MONTH = 31;
    private final static int MONTHS_PER_YEAR = 12;
    private int[] birthDayStats;
    private int[] birthMonthStats;
    private ArrayList<Person> people;

    /**
     * Constructor for objects of class Analyzer
     */
    public Analyzer() {
        this.people = new ArrayList<Person>();
        this.birthDayStats = new int[Analyzer.DAYS_PER_MONTH];
        this.birthMonthStats = new int[Analyzer.MONTHS_PER_YEAR];
    }

    public void addPerson(String name, int birthDay, int birthMonth, int
            birthYear) {
        Person person = new Person(name, birthDay, birthMonth, birthYear);
        if (person.getBirthDay() != -1 || person.getBirthMonth() != -1) {
            people.add(person);
            birthMonthStats[birthMonth - 1]++;
            birthDayStats[birthDay - 1]++;
        } else {
            System.out.println("Your current Birthday is " + birthDay + " or "
                    + birthMonth + " which is not a correct number 1-31 or 1-12 please " +
                    "put in a correct number ");
        }
    }

    public void printPeople() { //prints all people in form: “  Name: Tom   Month: 5   Day: 2  Year: 1965”
        int index = 0;
        while (index < people.size()) {
            Person person = (Person) people.get(index);
            System.out.println(person);
            index++;
        }
    }

    public void printMonthList() { //prints the number of people born in each month
        // Sample output to the right with days being similar
        int index = 0;
        while (index < birthMonthStats.length) {
            System.out.println("Month number " + (index + 1) + " has " +
                    birthMonthStats[index] + " people");
            index++;
        }
    }

    public Person removePerson(String name) {// removes the person from the arrayList
    }
}

最佳答案

/**
 * Removes the {@code Person} with the given {@code name} from the list
 * @param name the {@code Person}'s name
 * @return the {@code Person} removed from the list or {@code null} if not found
 */
public Person removePerson(String name) {
    if (name != null) {
        for (Iterator<Person> iter = people.iterator(); iter.hasNext(); ) {
            Person person = iter.next();
            if (name.equalsIgnoreCase(person.getName())) {
                iter.remove();
                return person;
            }
        }
    }
    return null;
}

请参阅java.util.Iterator#remove()方法。

<小时/>

周二学习奖励:

如果您想在列表中更快地查找名称,您应该考虑使用 java.util.Map实现:

HashMap<String,Person> people;

您可以以智能方式添加 Person 对象,以使搜索不区分大小写:

people.put(name.toLowerCase(), new Person(name, ...));

...您的 removePerson 方法将变为:

public Person removePerson(String name) {
    if (name != null)
        name = name.toLowerCase();
    return people.remove(name);
}

请参阅java.util.Map#remove()方法。

关于java - 如何编写一个删除方法来从数组列表中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46427737/

相关文章:

java - 如何有效地从 Spring Data JPA 的 findAllById 方法中知道丢失的项目?

java - 带 2 对公钥/私钥的 SSL

java - 如何将 Retrofit 2 响应保存到 SharedPreferences 中

java - revalidate() 和 repaint() 没有更新我的 JPanel

java - 使用 ints 作为 prop.setProperty()

java - ArrayList 和修改其中包含的对象

java - 具有 Avro 记录的 Kafka Streams TopologyTestDriver 的架构注册问题

java - 创建一个仅包含字符串的 ArrayList。使用增强的 for 循环打印

Java 数组列表包含并设置值

java - 将最后一个元素的信息添加到 ArrayList 的末尾