How to delete specific element from array list

Im trying but its not good. Here is all code:

    //creating passener object

    Passenger passenger1 = new Passenger(1, "Stefan", "Jankovic", "[email protected]", 3000);
    Passenger passenger2 = new Passenger(2, "Stefan", "Jankovic", "[email protected]", 3000);
    Passenger passenger3 = new Passenger(3, "Stefan", "Jankovic", "[email protected]", 3000);
    Passenger passenger4 = new Passenger(4, "Stefan", "Jankovic", "[email protected]", 3000);

Adding that passenger into array list:

ArrayList<Passenger> passengerArrayList = new ArrayList<>();
    passengerArrayList.add(passenger1);
    passengerArrayList.add(passenger2);
    passengerArrayList.add(passenger3);
    passengerArrayList.add(passenger4);

Im trying to delete specific passenger from array like this:

@Override
public void deletePassenger(ArrayList<Passenger> passengerList) {

    System.out.println("---Passengers list--");
    for (Passenger tempPassenger : passengerList) {
        System.out.println(tempPassenger);
        System.out.println("If you want to see options menu, enter 6");
    }

    System.out.println("Enter ID of passenger that you want to delete!");
    int id = scanner.nextInt();
    scanner.nextLine();

    System.out.println("---Passengers list--");
    for (Passenger tempPassenger : passengerList) {
        System.out.println(tempPassenger);
        passengerList.remove(id);
    }


}

This is error:

    ---Passengers list--
Passenger{id=1, firstName='Stefan', lastName='Jankovic', email='[email protected]', balance=3000.0}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.remove(ArrayList.java:492)
    at com.cv.controllers.PassengerControllerImpl.deletePassenger(PassengerControllerImpl.java:394)
    at com.cv.demo.Main.main(Main.java:66)

Answer

The problem you have right now is you’re just removing an element from the list’s index based on user input while you should make sure list is of that size. Second thing, You can’t remove an element from the list while browsing it via the forEach loop, you would get a ConcurrentModificationException , read concurrentModificationException. The way to do it would be using an iterator, check

Iterator<Passenger> itr = passengerList.iterator();
while (itr.hasNext()){
    Passenger p = itr.next();
    if (id == p.getId()) {
        itr.remove();
        break;
    }
}