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;
}
}
Answer from Manish Karki on Stack Overflowjava - How to delete specific element from array list - Stack Overflow
How do I remove an object from an arraylist and delete it in java?
Cannot remove odd elements from ArrayList in Java.
Question and solution: How to delete or add an object to/from array list while iterating it.
Videos
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;
}
}
if you want to remove passenger from ArrayList using your passenger id, you can create your own delete function.
public void removeList(ArrayList<Passenger> passengerList, int passengerId) {
for (int i = 0; i<passengerList.size(); i++) {
if (passengerList.get(i).getId() == passengerId) {
passengerList.remove(i);
}
}
}
You can use 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--");
removeList(passengerList, id);
}
So, basically I want to do a shopping list that you can put the price, quantity, name. I want to implement a button that deletes an object. I have tried doing "int s = objectList.indexOf(myobject); objectList.remove(s); myobject=null;", but it keeps giving me errors. Please help me, if you need any code from my project, I will give it. Btw, the object extends JPanel