本文介绍了清单VS列表迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

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?

推荐答案

他们做同样的事情 - 增强循环是只为手写版本语法糖(为iterables;数组是略有不同)。除非你需要明确地迭代器(例如调用删除())我会使用的第一个版本。

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.

这篇关于清单VS列表迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:09
查看更多