1. Iterator is a design pattern and is a light-weight container.
2. Iterator doesnt need to know what the collection is (i.e. a List or sth else )
3. Using iterator ,we can remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering.
4. Similarly, forEach is not usable for loops where you need to replace elements in a list or array as you traverse it, but Iterator can be used.
5 .Finally, forEach is not usable for loops that must iterate over multiple collections in parallel.
http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html
Welcome Message
Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.
Top Navigation Menu
Showing posts with label Iterator. Show all posts
Showing posts with label Iterator. Show all posts
January 19, 2010
November 13, 2009
Fail fast and fail safe iterator
Fail Fast :
When we iterate over a collection, if during iteration, we modify the collection , then the iteration halts and we get "ConcurrentModificationException" (e.g Hashtable)
Fail Safe :
During iteration, a separate copy of the colleciton object is created and iteration occurs on that. So if we modify it during the iteration process, it wont throw an exception.(e.g HashMap)
Best Explanation (with example) : http://www.certpal.com/blogs/2009/09/iterators-fail-fast-vs-fail-safe/
When we iterate over a collection, if during iteration, we modify the collection , then the iteration halts and we get "ConcurrentModificationException" (e.g Hashtable)
Fail Safe :
During iteration, a separate copy of the colleciton object is created and iteration occurs on that. So if we modify it during the iteration process, it wont throw an exception.(e.g HashMap)
Best Explanation (with example) : http://www.certpal.com/blogs/2009/09/iterators-fail-fast-vs-fail-safe/
Subscribe to:
Posts (Atom)