0
class Emp {

    String ID, FName, LName, ASalary, StartDate;

    Emp(String _ID, String _FName, String _LName, String _ASalary, String _StartDate) {
        ID = _ID;
        FName = _FName;
        LName = _LName;
        ASalary = _ASalary;
        StartDate = _StartDate;
    }
}

ArrayList< Emp> Record = new ArrayList< Emp>();


 private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {                                          
        String ID;

        ID = IDin.getText();
     
        int firstIndex = Record.indexOf(ID);
        Record.remove(firstIndex);
        Display.setText("remove " + ID + " Indext of " + firstIndex);
}      

It returns -1 as it couldn't find ID in the ArrayList, I just need to get ID number and remove the entire ArrayList with that ID number

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
EverGreat
  • 15
  • 5
  • Your are storing EMP records but are searching use a String. – Scary Wombat Oct 22 '21 at 01:47
  • As per the javadocs *Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.* If you have an ID of `Fred` it will not be found because Your list does not contain a String Object `Fred` - see this answer https://stackoverflow.com/a/13139071/2310289 – Scary Wombat Oct 22 '21 at 01:48

1 Answers1

0

You can simply use removeIf and provide a predicate like this:

id = IDin.getText();
record.removeIf(emp -> emp.getId().equals(id)); //add null check if needed

boolean removeIf(Predicate<? super E> filter)

Removes all of the elements of this collection that satisfy the given predicate. Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller.

lkatiforis
  • 5,703
  • 2
  • 16
  • 35