Saurabh Kumar
Saurabh Kumar

Reputation: 16651

Whether iterating collection using a iterator is more effecient than normal iteration

I have a collection like follows:

  final List list = new ArrayList(3);

Is it effecient to do something like below

    for (final Iterator iter = list.iterator(); iter.hasNext();)
    {
        // do something
    }

OR

for(final Object obj : list){
// do something 
}

?

Upvotes: 2

Views: 71

Answers (1)

Paul Bellora
Paul Bellora

Reputation: 55213

The second example is just a shortcut syntax for the first one. They're essentially the same thing (assuming you call final Object obj = iter.next(); in your for loop).

The shortcut syntax, known as "for-each" or "enhanced for", is more typically used since it's cleaner, more intuitive, and as Péter Török notes avoids potential bugs. I only recommend the plain syntax when it's needed for its greater flexibility.

See this article for more information: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

Upvotes: 5

Related Questions