传统的 for循环来遍历一个集合:
// Not the best way to iterate over a collection!
for (Iterator<Element> i = c.iterator(); i.hasNext(); ) {
Element e = i.next();... // Do something with e
}
迭代数组的传统 for 循环的实例
// Not the best way to iterate over an array!
for (int i = 0; i < a.length; i++) {... // Do something with a[i]
}
迭代器和索引变量都很混乱——你只需要元素而已。
for-each 循环 (官方称为“增强的 for 语句”) 解决了所有这些问题
// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {... // Do something with e
}