通过Collection(这里是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) {
}
for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
type type = iterator.next();
}
- mike jones