-2

以员工记录程序为例,它将员工姓名、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?

   }
4

1 回答 1

0

如果您希望能够通过 ID 查找公司,我建议使用 HashMap 而不是 ArrayList。HashMap 允许您通过关联查找键来存储对象。这是文档: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);
于 2013-05-01T20:57:05.253 回答