ListIterator
In this chapter you will learn:
Use ListIterator
ListIterator
extends Iterator
to allow
bidirectional traversal of a list, and the modification of elements.
ListIterator
is generic interfaces:
interface ListIterator<E>
E
specifies the type of objects being iterated.
The methods declared by ListIterator
are
void add(E obj)
inserts obj into list in front of the element that will be returned by the next call to next( ).boolean hasNext( )
returns true if there is a next element. Otherwise, returns false.boolean hasPrevious( )
returns true if there is a previous element. Otherwise, returns false.E next( )
returns the next element.int nextIndex( )
returns the index of the next element. If there is not a next element, returns the size of the list.E previous( )
returns the previous element.int previousIndex( )
returns the index of the previoLangShortTitle:us element. If there is not a previous element, returns -1.void remove( )
removes the current element from the list.void set(E obj)
assigns obj to the current element.
import java.util.ArrayList;
import java.util.ListIterator;
/*from java2 s . c o m*/
public class Main {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
ListIterator<String> litr = al.listIterator();
while (litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
while (litr.hasPrevious()) {
String element = litr.previous();
System.out.println(element + " ");
}
}
}
ListIterator
can access the collection in either the forward
or backward direction and can modify an element. Otherwise, ListIterator
is used just
like Iterator
.
Next chapter...
What you will learn in the next chapter: