简体   繁体   中英

List vs List iterator

I have one list:

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?

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 (eg to call remove() ) I'd use the first version.

See section 14.14.2 of the Java Language Specification for more details of the exact transformation performed by the compiler.

Using an Iterator provides much safer access to the List from outside the defining class as you cannot accidentally override the entire List for example. You can only ever access one element at a time: the top one.

So the guideline we use is to only use the for each approach inside the defining class and whenever the List needs to be accessed from the outside an iterator has to be used. This also enforces the concept of keeping the logic of how to modify a member inside the class that contains it. All complex operations that are needed outside have to be implemented in public methods inside that class .

The first one is what you call an "enhanced for loop" which was introduced in JDK 1.5+

It is more convenient way of iterating through a list. Also, you do not need to do explicit castings if you are using that.

From the performance perspective, I don't think there isn't much difference between the two.

迭代器:它在需要时为您提供结果,并且不会在内存中获得所有结果

Enhanced for loop used iterator only inside it. So both are same.

第一个更清楚,但如果你想在访问列表时删除元素,你唯一的选择是迭代器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM