Java foreach和Iterator遍历List集合

Java中支持三种基本的遍历方式:

                    1.for循环

                    2.foreach循环

                    3.使用Iterator迭代器

我们只要分析以下两个;

2.foreach:foreach内部实际上也是采用了Iteratror的方式来实现,只不过Java编译器帮我们生成了这些代码;

foreach遍历List:

for (String str:list) {
    System.out.println(str);

}

3.Iterator:相比于传统的for循环,Iterator取代了显式的遍历计数器。所以基于顺序存储集合的Iterator可以直接按位置访问数据。但是iterator正常的实现都是需要保存当前遍历的位置,然后根据当前位置来向前或者向后移动指针。

Iterator<String> iterator = list.iterator();
while (iterator.hasNext())

System.out.println(iterator.next());

tips:当你不记得是该使用has.Next()还是用next()的时候,你可以去看一下源代码:

/**
 * Returns {@code true} if the iteration has more elements.
 * (In other words, returns {@code true} if {@link #next} would
 * return an element rather than throwing an exception.)
 *
 * @return {@code true} if the iteration has more elements
 */boolean hasNext();

不难看出,这里说明了has.Next()是一个boolean类型的值,并且当iterator有下一个元

素时,返回true;

/**
 * Returns the next element in the iteration.
 *
 * @return the next element in the iteration
 * @throws NoSuchElementException if the iteration has no more elements
 */

E next();

而next()函数单纯的只是返回迭代器中下一个元素

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值