-->

Iterator Vs Enumeration VS ListIterator in Java Collection

Posted by Admin on
Iterator , Enumeration and ListIterator are interface which  are used to iterate over the collections in Java.


  • Iterator provide iterator() function to iterate over collections.
  • Enumeration provide iterator() function to iterate over collections.
  • ListIterator provide listIterator() function to iterate over collections.


Enumeration :A class that implements Enumeration interface provides access to series of elements one at a time. You need to call nextElement() method to get next element in the series. Also hasMoreElements() method gives you status about the availability of next element in the series.
It has 2 methods :
1) nextElements()
2) hasMoreElements()

Iterator : Iterator is an improved version of Enumeration.All of the collection classes provides iterator() method to iterate through the collection. The iterator() method returns the Iterator object through which you can access the collection elements in an order. Enumeration also does the same purpose. The difference between Iterator and Enumerations is: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
It has three methods :
1)hasNext()-return true if iterator has more element[retun false if next() throws exception) 
2)next() - return the next element,it throw NoSuchElementException. 
3)remove() -Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. 

ListIterator : Using ListIterator, we can iterate all elements of a list in either direction. You can access next element by calling next() method, and also you can access previous element by calling previous() method on the list. 

Implementation :



import java.awt.List;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;

class Employee{
       String name;
       int age;
      
       Employee(){}
      
       Employee(String name, int age)
       {
              this.name = name;
              this.age =age;
       }
}


public class IteratorVsEnumerator {
      
       public static void main(String args[])
       {
             
              ArrayList<Employee> list = new ArrayList<Employee>();
              list.add(new Employee("ishant",24));
              list.add(new Employee("rahul",23));
              list.add(new Employee("pankaj",21));
              list.add(new Employee("aman",22));
      
              // printing elements using Enumerations 
              //and one thing i noticed that we cant enumeration with ArrayList
             
              Vector<String> lang = new Vector<String>();
        Enumeration<String> en = null;
        lang.add("JAVA");
        lang.add("JSP");
        lang.add("SERVLET");
        lang.add("EJB");
        lang.add("PHP");
        lang.add("PERL");
        en = lang.elements();
        while(en.hasMoreElements()){
            System.out.println(en.nextElement());
        }
      
             
              Iterator<Employee> itr = list.iterator();
             
              // deleting employee object with name ishant          
              while(itr.hasNext()){
                    
                     if(itr.next().name.equals("ishant"))
             {
                itr.remove();
             }
              }
       
             
              //printing the element using iterator interface
              itr = list.iterator();
              while(itr.hasNext()){
                      System.out.println(itr.next().name);
           }
             
              //printing elements using listIterator
              ListIterator<Employee> litr =list.listIterator();
             
        System.out.println("Elements in forward directiton");
        while(litr.hasNext()){
            System.out.println(litr.next().name);
        }
        System.out.println("Elements in backward directiton");
        while(litr.hasPrevious()){
            System.out.println(litr.previous().name);
        }
       
        //adding more elements using ListIterator
        litr =list.listIterator();
        litr.add(new Employee("varun",23));
       
        litr =list.listIterator();
       
        System.out.println("Elements in forward directiton");
        while(litr.hasNext()){
            System.out.println(litr.next().name);
        }
        System.out.println("Elements in backward directiton");
        while(litr.hasPrevious()){
            System.out.println(litr.previous().name);
        }
      
       }

}


How do you remove an entry from a Collection? and subsequently what is difference between remove() method of Collection and remove() method of Iterator, which one you will use, while removing elements during iteration?

Collection interface defines remove(Object obj) method to remove objects from Collection. List interface adds another method remove(int index), which is used to remove object at specific index. You can use any of these method to remove an entry from Collection, while not iterating. Things change, when you iterate. Suppose you are traversing a List and removing only certain elements based on logic, then you need to use Iterator's remove() method. This method removes current element from Iterator's perspective. If you use Collection's or List's remove() method during iteration then your code will throw ConcurrentModificationException. That's why it's advised to use Iterator remove() method to remove objects from Collection.


What is difference between Iterator and Enumeration?

Iterator duplicate functionality of Enumeration with one addition of remove() method and both provide navigation functionally on objects of Collection.Another difference is that Iterator is more safe than Enumeration and doesn't allow another thread to modify collection object during iteration except remove() method and throws ConcurrentModificaitonException.


Why ListIterator has add() method but Iterator doesn't or Why add() method is declared in ListIterator and not on Iterator.

Answer : ListIterator has add() method because of its ability to traverse or iterate in both direction of collection. it maintains two pointers in terms of previous and next call and in position to add new element without affecting current iteration.

When does ConcurrentModificationException occur on iteration?

When you remove object using Collection's or List's remove method e.g. remove(Object element) or remove(int index), instead of Iterator's remove() method than ConcurrentModificationException occur. As per Iterator's contract, if it detect any structural change in Collection e.g. adding or removing of element, once Iterator begins, it can throw ConcurrentModificationException. 


What is difference between fail-fast and fail-safe Iterators?

This is relatively new collection interview questions and can become trick if you hear the term fail-fast and fail-safe first time. Fail-fast Iterators throws ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing or modifying objects on underlying collection. They are called fail-fast because they try to immediately throw Exception when they encounter failure. On the other hand fail-safe Iterators works on copy of collection instead of original collection



What is the difference between iterator and ListIterator ?

Iterator traverse the element in forward direction only and List Iterator traverse the element in both the direction.

Iterator is used with Set,List and Queue whereas ListIterator can be used with List only.




Implement our own Iterator : 





No comments:

Post a Comment