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()函数单纯的只是返回迭代器中下一个元素