如何删除存储在数组列表中的选定值?

时间:2013-05-01 20:51:41

标签: java arrays list

获取员工记录程序,该程序存储员工姓名,ID#,年薪和在ArrayList中雇用的日期。

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

String ID, firstName, lastName, annualSal, startDate;

存储信息。

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);
        inventory.add(c);
    }

这会在调出时输出列表中的信息。

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

        String temp = "";

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

此按钮将删除所选信息(通过输入ID#)并删除员工的记录。

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

//Code here on how to delete an unknown variable stored in array, possible to use getText?

   }

1 个答案:

答案 0 :(得分:0)

如果您希望能够按ID查找公司,我建议使用HashMap而不是ArrayList。 HashMap允许您通过关联查找键来存储Object。这是文档:http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

以及一些有用的命令:

HashMap<Integer,Company> inventory = new HashMap<Integer,Company>();

inventory.put(ID,c);

Company c = inventory.get(ID);

inventory.remove(ID);