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
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 :
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
Hi,
ReplyDeleteThe functionality of Enumeration interface is duplicated by the Iterator interface.
Iterator has a remove() method while Enumeration doesn’t. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.
to read more see here difference between iterator and enumeration
Thanks
Javin
Difference between FIX4.2 vs FIX4.4