开发者

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

开发者 https://www.devze.com 2023-04-11 04:52 出处:网络
This question already has answers here: Is there a way to access an iteration-counter in Java's for-each loop?
This question already has answers here: Is there a way to access an iteration-counter in Java's for-each loop? (16 answers) Closed 5 years ago.

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..
            }
        }
    }
}


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++;
}


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

For getting the index, you can use List.indexOf(object).

I have used these techniques for getting index of current object in a list. For example you given above, the removal can be done using two ways.

  • Using object instance to remove object.
 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(bd)  // Object Instance here..
                }
            }
        }
    }
  • Using List.indexOf(index)
 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(l.indexOf(bd))  // index Number here..
                }
            }
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消