简体   繁体   中英

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.

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. 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(). 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.

These methods are equals() and hashCode(), a brief explanation can be found here and here .

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.

If you're working with Set and Maps you should add equals and hashcode implementations.

I'm a big fan of the Objects Util class. Its integration do nullchecks for you as well. 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. 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 . Also, you can use directly inventory.remove(position) if you know the position of the record you want to remove

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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