Is it possible to find the present index in an enhanced for loop? If so how?
I am aware we can check it with an extra variable. But is there any other way.
public boolean cancelTicket(Flight f, Customer c) {
List<BookingDetails> l = c.getBooking();
if (l.size() < 0) {
return false;
} else {
for (BookingDetails bd : l) {
if(bd.getFlight()==f){
l.remove() // Index here..
}
}
}
}
No. If you need the index, I suggest you use an ordinary for-loop.
However, you don’t actually seem to need the index in this situation. Unless you’re dealing with some really strange type of list, you could go with an
Iteratorand use theIterator.remove()method, like this: