ListIterator is an interface in the collection framework. Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an listIterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. Iterator gives you the ability to access the collection either in forward direction or backward direction.
It has methods hasNext(), hasPrevious(), next() and previous().
hasNext( ) returns false when the end of the list has been reached. Otherwise it returns true.
hasPrevious() returns true if this list iterator has more elements when traversing the list in the reverse direction. Otherwise it returns false.
obtain each element by calling next( ).
previous() returns the previous element in the list.
public class sample {
public static void main(String[] args) {
//create an object of ArrayList
ArrayList aList = new ArrayList();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
//Get an object of ListIterator using listIterator() method
ListIterator listIterator = aList.listIterator();
System.out.println(" forward direction using ListIterator");
while(listIterator.hasNext())
System.out.println(listIterator.next());
System.out.println("reverse direction using ListIterator");
while(listIterator.hasPrevious())
System.out.println(listIterator.previous());
}
}
Output :
forward direction using ListIterator
1
2
3
4
5
reverse direction using ListIterator
5
4
3
2
1
It has methods hasNext(), hasPrevious(), next() and previous().
hasNext( ) returns false when the end of the list has been reached. Otherwise it returns true.
hasPrevious() returns true if this list iterator has more elements when traversing the list in the reverse direction. Otherwise it returns false.
obtain each element by calling next( ).
previous() returns the previous element in the list.
public class sample {
public static void main(String[] args) {
//create an object of ArrayList
ArrayList aList = new ArrayList();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
//Get an object of ListIterator using listIterator() method
ListIterator listIterator = aList.listIterator();
System.out.println(" forward direction using ListIterator");
while(listIterator.hasNext())
System.out.println(listIterator.next());
System.out.println("reverse direction using ListIterator");
while(listIterator.hasPrevious())
System.out.println(listIterator.previous());
}
}
Output :
forward direction using ListIterator
1
2
3
4
5
reverse direction using ListIterator
5
4
3
2
1
0 comments:
Post a Comment