姬長信(Redy)

Java:迭代集合的最佳方式(此处为ArrayList)


今天,当我得到一段已经使用过数百次的代码时,我很乐意编写代码:

Iterating through a Collection (here ArrayList)

出于某种原因,我实际上看了Eclipse的自动完成选项,它让我想知道:

以下循环比其他循环更好用?

经典数组索引循环:

for (int i = 0; i < collection.length; i++) {
  type array_element = collection.get(index);
}

Iterator hasNext()/ next():

for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
  type type = (type) iterator.next();   
}

我最喜欢的,因为它写得如此简单:

for (iterable_type iterable_element : collection) {

}