简体   繁体   English

如何从对象数组列表中删除项目?

[英]how can i remove items from an arraylist of objects?

I'm kinda new to programming with Java (netbeans) and I'm having trouble removing items from an arraylist for employee records after quite some time trying out different options. 我是使用Java(netbeans)编程的新手,在尝试了多种选择之后,无法从数组列表中删除员工记录的项目。

I need to accept user input for first and last name, ID, annual salary, and start date, then add this information to an array to be displayed. 我需要接受用户输入的名字和姓氏,ID,年薪和开始日期,然后将此信息添加到要显示的数组中。 I can add and display the information quite easily but removing the items using the same methods isn't working for me. 我可以很容易地添加和显示信息,但是使用相同的方法删除项目对我来说不起作用。 Doing inventory.add() works fine, but not inventory.remove(). 进行stocking.add()可以正常工作,但不会执行stocking.remove()。 This is what I have done right now, using the techniques that I have to use for the sake of this activity. 这是我现在所做的,使用了为此活动必须使用的技术。

ArrayList <records> inventory = new ArrayList <records>();

    class records {
        String IDNumber, firstName, lastName, annualSalary, startDate;
        records (String temp1, String temp2, String temp3, String temp4, String temp5) {
            IDNumber = temp1;
            firstName = temp2;
            lastName = temp3;
            annualSalary = temp4;
            startDate = temp5;
        }
    }


    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          

    String IDNumber, firstName, lastName, annualSalary, startDate;

    records eRec;

    IDNumber = IDNumberInput.getText();
    firstName = firstNameInput.getText();
    lastName = lastNameInput.getText();
    annualSalary = annualSalaryInput.getText();
    startDate = startDateInput.getText();

    eRec = new records(IDNumber, firstName, lastName, annualSalary, startDate);
    inventory.add(eRec);

    }                                         

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             

    String IDNumber, firstName, lastName, annualSalary, startDate;

    records eRec;

    IDNumber = IDNumberInput.getText();
    firstName = firstNameInput.getText();
    lastName = lastNameInput.getText();
    annualSalary = annualSalaryInput.getText();
    startDate = startDateInput.getText();

    eRec = new records(IDNumber, firstName, lastName, annualSalary, startDate);
    inventory.remove(eRec);

    }                                            

    private void listButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           

    String temp="";

        for (int x=0; x<=inventory.size()-1; x++) {
            temp = temp + "- " + inventory.get(x).firstName + " "
                    + inventory.get(x).lastName + " — ID Number: "
                    + inventory.get(x).IDNumber + "\nAnnual Salary: $"
                    + inventory.get(x).annualSalary + " — startDate: "
                    + inventory.get(x).startDate + "\n";
        }
        outputArea.setText(temp);   

    }                                          

In your case, when you try to remove an element, you must have in mind that you want to remove exact the same object that you are passing in the parameters, BUT TO DO THAT, you must implement 2 methods that will help you in the process and that you must understand first. 在您的情况下,当您尝试删除一个元素时,必须牢记要删除与您传入参数完全相同的对象,但要做到这一点,您必须实现2种方法来帮助您过程,您必须先了解。

These methods are equals() and hashCode(), a brief explanation can be found here and here . 这些方法是equals()和hashCode(), 这里这里都有简要说明。

Now talking about your example, your records class must implement both methods, something like this: 现在谈论您的示例,您的记录类必须实现这两种方法,如下所示:

    @Override
    public boolean equals(Object o) {
    if (this == o) {
        return true;
    }

    if (o == null || getClass() != o.getClass() || !(o instanceof Records)) {
       return false;
    }

    Records r = (Records) o;

    return (IDNumber.equals(r.getIDNumber()) && 
        firstName.equals(r.getFirstName()) && 
        lastName.equals(r.getLastName()) && 
        annualSalary.equals(r.getAnnualSalary()) && 
        startDate.equals(r.getStartDate()));
    }

    @Override
    public final int hashCode() {
        int result = 17;
        if (IDNumber != null) {
            result = 31 * result + IDNumber.hashCode();
        }
        if (firstName != null) {
            result = 31 * result + firstName.hashCode();
        }
        if (lastName != null) {
            result = 31 * result + lastName.hashCode();
        }
        if (annualSalary != null) {
            result = 31 * result + annualSalary.hashCode();
        }
        if (startDate != null) {
            result = 31 * result + startDate.hashCode();
        }
        return result;
   }

After doind that, you can accomplish what you are trying to do, removing the elements by informing values into your inputTexts like you did. 完成上述操作之后,您就可以完成您想做的事情,通过像以前一样将值通知到inputTexts中来删除元素。

If you're working with Set and Maps you should add equals and hashcode implementations. 如果使用Set和Maps,则应添加equals和hashcode实现。

I'm a big fan of the Objects Util class. 我是Objects Util类的忠实粉丝。 Its integration do nullchecks for you as well. 它的集成也为您执行nullchecks。 Also the code looks more clean. 代码看起来也更干净。

public class Records {

    String idNumber, firstName, lastName, annualSalary, startDate;

    Records(String idNumber, String firstName, String lastName, String annualSalary, String startDate) {
        this.idNumber = idNumber;
        this.firstName = firstName;
        this.lastName = lastName;
        this.annualSalary = annualSalary;
        this.startDate = startDate;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Records)) {
            return false;
        }
        Records that = (Records) o;
        return Objects.equals(idNumber, that.idNumber)
                && Objects.equals(firstName, that.firstName)
                && Objects.equals(lastName, that.lastName)
                && Objects.equals(annualSalary, that.annualSalary)
                && Objects.equals(startDate, that.startDate);
    }

    @Override
    public int hashCode() {
        return Objects.hash(idNumber, firstName, lastName, annualSalary, startDate);
    }
}

One more thing i changed to the record class. 我又改变了一个记录类。 Usually you should write class names with UpperCamelCase and keep variable names start with small camelCase. 通常,您应该使用UpperCamelCase编写类名,并使变量名以小camelCase开头。 And to keep it clean, use meaningful names for parameter, class names and variables. 为了保持整洁,请对参数,类名和变量使用有意义的名称。 Later on it will help a lot to read and understand the code if it is getting more complexity. 稍后,如果变得越来越复杂,它将有助于阅读和理解代码。

Intead of creating a new record in your removeButtonActionPerformed method, you can first get your record with ArrayList.get() and then remove it using inventory.remove . 创造你的新纪录这一翻译removeButtonActionPerformed方法,你可以先得到你的记录ArrayList.get()然后使用删除inventory.remove Also, you can use directly inventory.remove(position) if you know the position of the record you want to remove 另外,如果您知道要删除的记录的位置,则可以直接使用inventory.remove(position)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM