Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to find the present index in an enhanced for loop? [duplicate]

Tags:

java

for-loop

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..
            }
        }
    }
}
like image 505
rgksugan Avatar asked Oct 07 '11 11:10

rgksugan


People also ask

Which is a limitation of an enhanced for loop?

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.

What is the main advantage of an enhanced for loop?

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.

Do enhanced for loops traverse the complete array sequentially?

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.


2 Answers

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; } 
like image 110
aioobe Avatar answered Sep 25 '22 02:09

aioobe


Yes, Use a counter before the for statement. as such:

int i = 0;
for (int s : ss)
{
   // Some Code
   System.out.println(i);

   i++;
}
like image 35
Izzy Kiefer Avatar answered Sep 22 '22 02:09

Izzy Kiefer