Monday, December 6, 2010

Iterator vs For Each

In many cases we need to iterate over collections , earlier versions of java provides few mechanisms to accomplish that task such as Iterator ,Enumerations before we going through new java feature for each ,lets discuss what are the diference's between those two interfaces

Enumerations is the older one among those two types it simple iterate through the Collection and it is not allow programmer to modify(allow remove) the collection while traverse.But more advance feature Iterator give freedom to developer to modify the iterator .

@see here is the source code of the Iterator

example of enumerations

for (Enumeration e = v.elements(); e.hasMoreElements();)
System.out.println(e.nextElement());

But there is a disadvantage with Iterator that it does not allow to traverse to bi directions and java language introduce a new feature called ListIterator it extends Iterator interface this new iterator allow developer to move bi direction.so we can iterate forward and backward
@see source code of ListIterator


Note : when we need to iterate through the collection just reconsider what is the actual need and then use appropriate mechanism rather than selecting Iterator interface for all :D and frequently going throw java docs it save us from many development errors .And don not forget to use java generics with collections because generics are more useful with collections.hopes to discuss generics in next article so stay in touch

Back to the main topic
The question is why we asked to use new "for each" loop,even Iterator interfaces(including ListIterator as well) are full filling most of the requirements,the simple answer is iteration over collections are uglier than than it should be and using Iterators are opportunity for errors
.Because coding is not just giving solutions for a problems ,we have to maintain readability of the code those kind of iterations are reduce the readability of the code,the lack of readability guide you to critical coding errors.
Following is a nice article that you may have gone through if not go through follow article it is no use of including it in side this blog :D
@see For-Each
if you don't have enough time to go through it follow is a simple demonstration how for each improves readability of the code
example :




























is improved for each more nicer ? if so get use to that coding standards.

by the way just keep in mind that every programmer is doing mistakes even very experts,one way of avoiding those mistake is keep nice and clean code so make sure to use such mechanism to improve your readability of the code