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
}
?
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
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.