Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List vs List iterator

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?

like image 319
Swapnil Sonawane Avatar asked Dec 07 '11 06:12

Swapnil Sonawane


3 Answers

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.

like image 135
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet


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.

like image 31
Pete Avatar answered Sep 28 '22 08:09

Pete


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

like image 22
daydreamer Avatar answered Sep 28 '22 08:09

daydreamer