Tuesday, September 20, 2016

Iterator || List Iterator

  1. Iterator
a.       Belongs to collection framework
b.      Can traverse the collection and access data
c.       List and set provide iterator
d.      Map does not provide iterator but we can apply it on keyset or valueset
e.       boolean hasNext()
f.       object next(): before getting next value of collection check for hasnext()
g.      void remove()
h.      Enumerator does not have remove method
i.        Thread-safe as it does not allow any other thread to modify collection when same thread is iterating in collection. If this happens concurrentModificationException is thrown
j.         
  1. ListIterator
a.       Used to traverse collection like Arraylist and hashSet in both direction using methods like previous() and next()
b.      Does not keep current index and its current position is determined by call to next() or previous() based on direction of traversing
c.       Has add() method which can add elements in collection while iterating over it.

Fail Fast
a.       Work on original collection
b.      Fail-fast iterators fail as soon as changes are made in the structure of collection(adding, removing or updating) when one thread is iterating over collection
c.       Modification count is maintained and if thread realizes it is changed and throws ConcurrentModificationException
d.      This is not guaranteed behavior since  it is done on best effort and does not involve synchronization
Fail-Safe
a.       Does not throw any exception when modification is done while one thread is iterating over it since they work on clone of iterator and not the original

No comments:

Post a Comment