java for list i,Java的foreach循环:for(Integer i:list){...}

这篇博客讨论了在使用Java 5的for-each循环时,如何检查是否已经到达列表的最后一个元素。作者提到了两种方法:一种是通过在循环内部使用计数器来判断,另一种是使用传统的for循环或迭代器,这两种方法都可以提供当前索引信息。文章强调,当需要获取当前索引时,有时使用旧的语法可能是更好的选择。
摘要由CSDN通过智能技术生成

When I use JDK5 like below

ArrayList list = new ArrayList();

for (Integer i : list) {

//cannot check if already reached last item

}

on the other hand if I just use an Iterator

ArrayList list = new ArrayList();

for (Iterator i = list.iterator(); i.hasNext();) {

//i can check whether this is last item

if(i.hasNextItem()){

}

}

How can I check if I've already reached last item with for (Integer i : list) {

解决方案

One way to do that is to use a counter:

ArrayList list = new ArrayList();

...

int size = list.size();

for (Integer i : list) {

...

if (--size == 0) {

// Last item.

...

}

}

Edit

Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a for loop or the iterator, as everything you win when using the Java5 syntax will be lost in the loop itself...

for (int i = 0; i < list.size(); i++) {

...

if (i == (list.size() - 1)) {

// Last item...

}

}

or

for (Iterator it = list.iterator(); it.hasNext(); ) {

...

if (!it.hasNext()) {

// Last item...

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值