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());
}
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.
Example:
/*ListIterator*/
while(itr.hasPrevious())