如何从数组列表中删除所选变量?

时间:2013-05-01 22:32:52

标签: java arrays list variables

这是一个程序,用于将员工的信息(工资,姓名,ID#,雇用日期)存储在数组列表中。当被调用时(在按下'listButton'之后),它会在一个字段中列出这些信息供雇主查看。员工需要从列表中删除一个员工,还有一个removeButton,那么雇主可以从员工列表中删除一个名字?

public class EmployeeView extends FrameView {

    class Company {
        String ID, firstName, lastName, annualSal, startDate, mileage;

        Company (String _ID, String _firstName,String _lastName, String _annualSal, String _startDate) {
            ID = _ID;
            firstName = _firstName;
            lastName = _lastName;
            annualSal = _annualSal;
            startDate = _startDate;
        }
    }

    /** Define the ArrayList */
    ArrayList <Company> employee = new ArrayList <Company>();

    String ID, firstName, lastName, annualSal, startDate;

    public EmployeeView(SingleFrameApplication app) {
       //GUI stuff...
    }

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

        ID = IDField.getText();
        firstName = firstNameField.getText();
        lastName = lastNameField.getText();
        annualSal = annualSalField.getText();
        startDate = startDateField.getText();

        Company c = new Company(ID, firstName, lastName, annualSal, startDate);
        employee.add(c);
    }

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

        String temp = "";

        for (int x=0; x<=employee.size()-1; x++) {
            temp = temp + employee.get(x).ID + " "
                    + employee.get(x).firstName + " "
                    + employee.get(x).lastName + " "
                    + employee.get(x).annualSal + " "
                    + employee.get(x).startDate + "\n";
        }
        employeeTArea.setText(temp);

}

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
    //My attempt... it didn't do anything though           
            int remove = 0;

            for (int j = 0; j < employee.size()-1; j++) {
                if (remove == Integer.parseInt(IDField.getText())) {

                   employee.remove(j);
                }
            }
    }

2 个答案:

答案 0 :(得分:2)

您正在初始化remove=0,您要做的是:

for (int j = 0; j < employee.size()-1; j++) {
                if (j == Integer.parseInt(IDField.getText())) {
                   employee.RemoveAt(j);
                }
            }

您不需要删除变量。这是因为IDField.getText()是您要从employee

中删除的ArrayList的索引

答案 1 :(得分:0)

您可以取消for循环,只需执行employee.remove(company)