List It Erator
List It Erator
By using Enumeration and Iterator we can Move Only towards Forward Direction and
we
can’t Move Backward Direction. That is these are Single Direction Cursors but Not
Bi-
Direction.
By using Iterator we can Perform Only Read and Remove Operations and we can't
Perform
Addition of New Objects and Replacing Existing Objects.
To Overcome these Limitations we should go for ListIterator.
3) ListIterator:
ListIterator is the Child Interface of Iterator.
Methods:
ListIterator is the Child Interface of Iterator and Hence All Iterator Methods by
Default
Available to the ListIterator.
Example :
package list;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListDemo {
System.out.println("Forward Direction");
while(listIterator.hasNext()) {
Object next = listIterator.next();
System.out.println(next);
}
System.out.println("Backword Direction");
while (listIterator.hasPrevious()) {
Object previous = listIterator.previous();
System.out.println(previous);
}
}
}
Example :
package list;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
System.out.println("Forward Direction");
while(listIterator.hasNext()) {
Object next = listIterator.next();
System.out.println(next);
System.out.println(listIterator.nextIndex());
}
System.out.println("Backword Direction");
while (listIterator.hasPrevious()) {
Object previous = listIterator.previous();
System.out.println(previous);
System.out.println(listIterator.previousIndex());
}
}
}
Example :
Example :
package list;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
System.out.println("Forward direction");
while (listIterator.hasNext()) {
Object next = listIterator.next();
System.out.println(next);
if(next.equals(99)) {
listIterator.remove();
}
System.out.println(al);
}
}
Example :
package list;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
System.out.println("Forward direction");
while (listIterator.hasNext()) {
Object next = listIterator.next();
System.out.println(next);
if(next.equals(99)) {
listIterator.add(333);
}
System.out.println(al);
}
}
Example :
package list;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
System.out.println("Forward direction");
while (listIterator.hasNext()) {
Object next = listIterator.next();
System.out.println(next);
if(next.equals(99)) {
listIterator.set(333);
}
System.out.println(al);
}
}