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

47

在增强型for循环中,能否找到当前的索引?如果可以,如何实现?

我知道我们可以使用额外变量来检查索引。但是否还有其他方法呢?

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

6
这个代码没有意义:if (list.size() < 0)。也许你想要使用 == 吗?(意思是“如果列表大小等于0”) - Bruno Reis
1
请检查以下内容。https://dev59.com/3nM_5IYBdhLWcg3w2XLw - Vaandu
3
即使你有索引,尝试在增强for循环中从列表中删除元素也会导致ConcurrentModificationException异常。请像@aioobe建议的那样使用迭代器。 - John B
3个回答

43

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

不行。如果你需要索引,建议使用普通的for循环。

但是,在这种情况下,你似乎实际上并不需要索引。除非你处理某种非常奇怪的列表类型,否则可以选择使用Iterator并使用Iterator.remove()方法,就像这样:

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

7
在这种情况下,你不需要索引来执行删除操作。而且,你不能使用索引来执行删除操作,因为如果你这样做,会导致ConcurrentModificationException异常。就像aioobe所说的那样,正确的方法是使用Iterator.remove() - Tom Anderson

18

是的,在for语句之前使用计数器,像这样:

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

   i++;
}

1
最佳和最有效的答案;-) - BullyWiiPlaza
虽然这是最直接的方法,但在使用continue语句时必须格外小心。基本上,无论在for循环的主体中的哪个位置使用continue关键字,都必须在之前加上i++指令,否则可能会发生一些奇怪的事情。为了避免担心这个问题,可以使用标准的for循环,在第一行做类似于Item item = list.get(i)的操作。这样你就可以同时获得索引和对象了。 - undefined

10

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

要获取索引,您可以使用List.indexOf(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..
                }
            }
        }
    }

15
List.indexOf 的时间复杂度为 O(n),因此我通常避免使用它。 - Matt Sgarlata
6
同时,indexOf 方法总是返回列表中对象的第一个出现位置,这可能并不是您想要的结果。 - IrishDubGuy
5
读者注意!这绝对不是正确的方法!它不仅非常慢(O(n^2)),而且可能是错误的(例如,对于列表中的重复值)。 - Benjamin Maurer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接