源码

首页 » 归档 » 源码 » Java:迭代集合的最佳方式(此处为ArrayList)

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) {

}
(0)

本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/javadiedaijihedezuijiafangshicichuweiarraylist.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:9 月 26, 2019 at 04:51 上午

热评文章