本文介绍了列表与列表迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表:
List<Object> myList = new ArrayList<Object>();
要从这个列表中获取,有两种方法:
To get from this list there are two methods:
1.
for(Object obj : myList )
{
// some code
}
2.
Iterator<Object> objIt = myList.iterator();
while(obj.hasNext()) {
Object obj = (Object)objIt.next();
// some code
}
我的问题是哪个内存高效且迭代速度快?
My question is which one is memory efficient and iterates fast?
推荐答案
他们做同样的事情 - 增强的 for
循环只是普通版本的语法糖(对于迭代器;对于数组,它稍微有点不同的).除非您明确需要迭代器(例如调用 remove()
),否则我会使用第一个版本.
They do the same thing - the enhanced for
loop is just syntactic sugar for the longhand version (for iterables; for arrays it's slightly different). Unless you need the iterator explicitly (e.g. to call remove()
) I'd use the first version.
请参阅 Java 语言规范的第 14.14.2 节 有关编译器执行的确切转换的更多详细信息.
See section 14.14.2 of the Java Language Specification for more details of the exact transformation performed by the compiler.
这篇关于列表与列表迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!