是否有可能在增强for循环中找到当前的索引? [英] Is it possible to find the present index in an enhanced for loop?

查看:393
本文介绍了是否有可能在增强for循环中找到当前的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在增强for循环中找到当前的索引?如果是这样的话?



我知道我们可以用一个额外的变量来检查它。但是有没有其他的方法。

$ pre $ $ $ $ l = c.getBooking();
if(l.size()<0){
return false; (bD.getFlight()== f){
l.remove()//此处为索引。(
)else {
for(BookingDetails bd:l){




$ b $ / code $ / pre

解决方案

是否可以在增强for循环中找到当前索引?


没有。如果你需要索引,我建议你使用一个普通的for循环。

然而,在这种情况下你并不需要索引。除非你正在处理一些非常奇怪的列表类型,你可以使用 Iterator 并使用 Iterator.remove()

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' ; bdIter = c.getBooking()。iterator();

if(!bdIter.hasNext())
return false;

while(bdIter.hasNext())
if(bdIter.next()。getFlight()== f)
bdIter.remove();

返回true;
}


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

这篇关于是否有可能在增强for循环中找到当前的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆