5

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?

ashatte
  • 5,442
  • 8
  • 39
  • 50
Swapnil Sonawane
  • 1,445
  • 3
  • 22
  • 37

6 Answers6

12

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.

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    I was about to give the similar answer. (Except the section 14... part.) +1 for speed. – Harry Joy Dec 07 '11 at 06:37
  • The Iterable interface (http://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html) says that is designed for the enhanced loop. Just wanted to point out the reference that they are exactly the same. – pimaster Dec 07 '11 at 06:37
5

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.

Jitendra A
  • 1,568
  • 10
  • 18
Pete
  • 10,720
  • 25
  • 94
  • 139
2

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.

Manish
  • 3,913
  • 2
  • 29
  • 45
2

Iterator : It gives you the result when needed and don't gets all the result in-memory

daydreamer
  • 87,243
  • 191
  • 450
  • 722
1

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

Selvakumar Ponnusamy
  • 5,363
  • 7
  • 40
  • 78
1

First one is more clear, but if you want to remove elements while visiting the list your only choice is an iterator.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119