Wednesday, September 3, 2014

Collection QA

Q1) Difference between Iterator and listIterator?


Answer

Iterator: can traverse only in forward direction.

ListIterator: can traverse in forward as well as backward direction.

It is an interface which provide the capability to traverse the list in both direction.
This interface also provide the facility to insert the element in a list that means we can perform removal as well as insertion.
Since List is ordered and it is indexed so we can travel it forward direction as well as backward direction , on the other hand Set is unordered that is why the listIterator() method is available only for List interface not for Set.

Example:

ArrayList<String> al=new ArrayList<String>();
al.add("one");
al.add("two");
al.add("three");

/*ListIterator*/
ListIterator itr=al.listIterator();
// start from 0th position and goes one by one till the end
while(itr.hasNext())
      {
         System.out.println(itr.next());
      }
// start from last position and goes one by one to the beginning
while(itr.hasPrevious()) 
      {
          System.out.println(itr.previous());
      }


Q2) Difference between fail-fast and fail-safe Iterator

Java provides the iterator to iterate the objects in the Collection. The rule is that the Collection should not be altered when iterating, if modified you will get the ConcurrentModificationException.

Fail-Fast Iterator

Iterator will fail if change in the collection. What ever the change it may be adding, update or removal of any object in the collection will throw the ConcurrentModificationException. Lets look it in the below example.

List al = new ArrayList();
al.add("1");
al.add("2");
al.add("3");
Iterator it = al.iterator();
int indexFlag = 1;
while(it.hasNext())
{
indexFlag++;
if(indexFlag==2)
{

al.remove(indexFlag);
}
}
O/P
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at FailIterator.main(FailIterator.java:20)

Fail-Safe Iterator

Whereas the fail-safe iterator will not throw any exception when the collection such asCopyOnWriteArrayList and ConcurrentHashMap  is modified. As it iterates on the copy of the collection
CopyOnWriteArrayList ca = new CopyOnWriteArrayList();
ca.add("1");
ca.add("2");
ca.add("3");
int indexFlag = 1;
Iterator it = ca.iterator();
while(it.hasNext())
{
indexFlag++;
if(indexFlag==2)
{
ca.remove(indexFlag);
}
}

How to Safely remove object from the collection while Iterating?

To remove the Object from the collection , instead of directly removing from the collection , you can use the remove() provided by the iterator.
List al = new ArrayList();
al.add("1");
al.add("2");
al.add("3");
int indexFlag = 2;
Iterator it = al.iterator();
while(it.hasNext()) {
it.remove();
}



No comments:

Post a Comment