List vs List of iterators

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 repeats quickly?

+5
source share
6 answers

They do the same thing - an extended loop for- it's just syntactic sugar for the longhand version (for iterables, for arrays it is slightly different). If you do not need an iterator explicitly (e.g. to call remove()), I would use the first version.

See section 14.14.2 Java Language Specifications for more information on the exact conversion performed by the compiler.

+12

Iterator - List class, List, . : .

, for each , , , . class, . , , public class.

+3

- , " ", JDK 1.5 +

. , , .

, .

+2

:

+2

. , .

+1

, , .

+1

All Articles