-2

Take an employee record program, which stores name of employee, ID#, annual salary and date hired in an ArrayList.

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

String ID, firstName, lastName, annualSal, startDate;

This stores the information.

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);
    }

This outputs the information in lists when called out.

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);

This button will remove selected information (by inputting ID#) and deletes employee's records.

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

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

   }
  • possible duplicate of [Deleting objects from an ArrayList in Java](http://stackoverflow.com/questions/1310532/deleting-objects-from-an-arraylist-in-java) – Eric May 01 '13 at 20:54
  • What's your question? Why don't you name the class Employee rather than Company, since it represents an employee? Also respect the Java naming conventions (methods start with a lowercase letter), and don't use public fields. – JB Nizet May 01 '13 at 20:55
  • where is the ID inputted into? – hrezs May 01 '13 at 20:56
  • @Eric similar, but not quite a duplicate. That question is asking how to delete all information stored in an array. I'm asking how to delete only one (Small ex. Apples, Bananas, Strawberries are the inputted fruits by the user) So what code you would you use to delete an unknown variable? (Since you are unaware what the user will be inputting) – user2340807 May 01 '13 at 20:59
  • @hrezs a Field, in this case IDField. – user2340807 May 01 '13 at 21:00

1 Answers1

0

If you want to be able to look up a Company by ID, I recommend using a HashMap instead of an ArrayList. A HashMap allows you to store an Object by associating a lookup key. Here's the documentation: http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

And some useful commands:

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

inventory.put(ID,c);

Company c = inventory.get(ID);

inventory.remove(ID);
David K
  • 1,296
  • 18
  • 39