使用整数值查找arraylist索引

时间:2017-12-17 07:35:46

标签: java arraylist

我的任务是使用employeeId删除arraylist索引。

这是我的代码,但我不知道如何找到索引。 有更好的方法吗?

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    employee workPerson;
    int employeeId = Integer.parseInt(employeeField.getText());
    String firstName = firstField.getText();
    String lastName = lastField.getText();
    int annualSalary = Integer.parseInt(salaryField.getText());
    workPerson = new employee(employeeId,firstName,lastName,"g",annualSalary);
    employeeList.add(workPerson);
}

class employee {
    int annualSalary,employeeId;
    String firstName, lastName,startDate;

    employee (int _employeeId,String _firstName, String _lastName, String _startDate,int _annualSalary) {
       employeeId = _employeeId;
       firstName = _firstName;
       lastName = _lastName;
       startDate = _startDate;
       annualSalary = _annualSalary;
    }
}

1 个答案:

答案 0 :(得分:0)

private int getEmployeeIndexByEmployeeId(List<employee> list, int desiredId) {
    for (employee employee : list) {
        if (employee.employeeId == desiredId)
            return list.indexOf(employee);
    }
}

然后在你的代码中使用:

    int employeeIndex = getEmployeeIndexByEmployeeId(list, desiredId);
    list.remove(employeeIndex);

那应该返回所需employeeId的索引。 确保您了解此处的逻辑并且不要只是复制粘贴