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..
}
}
}
}
The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order. Here, you do not have the option to skip any element because it does not work on an index basis. Moreover, you cannot traverse the odd or even elements only.
MAJOR BENEFIT: To sum up, the enhanced for loop offers a concise higher level syntax to loop over a list or array which improves clarity and readability.
Using the for each loop − Since JDK 1.5, Java introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
Is it possible to find the present index in an enhanced for loop?
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 Iterator
and use the Iterator.remove()
method, like this:
public boolean cancelTicket(Flight f, Customer c) { Iterator<BookingDetails> bdIter = c.getBooking().iterator(); if (!bdIter.hasNext()) return false; while (bdIter.hasNext()) if (bdIter.next().getFlight() == f) bdIter.remove(); return true; }
Yes, Use a counter before the for statement. as such:
int i = 0;
for (int s : ss)
{
// Some Code
System.out.println(i);
i++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With