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
forloop 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 callremove()) 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.