Java arraylist list iterator example

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class IterateElementsUsingListIterator {

	public static void main(String args[]) {
		List<Integer> list = new ArrayList<Integer>();

		/*
		 * add() method appends the specified element to the end of given list.
		 */
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);

		/*
		 * Note* : Difference between iterator and listIterator is that Iterator
		 * can only traverse in forward direction while listIterator can
		 * traverse in both direction(forward and backward)
		 */

		/*
		 * Returns a list iterator over the elements in given list
		 * 
		 * Note* : Here we are taking reference as ListIterator instead of Iterator otherwise ListIterator benefits can not be 
		 * taken.
		 */
		ListIterator<Integer> iterator = list.listIterator();

		System.out.println("Elements in ListIterator");
		while (iterator.hasNext())
			System.out.println(iterator.next());

		System.out.println("nTraversing in Previous direction");

		/*
		 * hasPrevious() method returns true if this list iterator has more
		 * elements when traversing the list in the reverse direction.
		 * 
		 * previous() method will returns the previous element in the list. This
		 * method may be called repeatedly to iterate through the list in
		 * backward direction.
		 */
		while (iterator.hasPrevious())
			System.out.println(iterator.previous());

		/*
		 * Returns a list iterator of the elements in given list in proper
		 * sequence, starting at the specified position in list. The specified
		 * index indicates the first element that would be returned by an
		 * initial call to next method. An initial call to previous would return
		 * the element with the specified index minus one.
		 */
		ListIterator<Integer> iteratorIndex = list.listIterator(3);
		System.out.println("nElements in ListIterator with Index");

		while (iteratorIndex.hasNext())
			System.out.println(iteratorIndex.next());

		System.out.println("nTraversing in Previous direction");
		while (iteratorIndex.hasPrevious())
			System.out.println(iteratorIndex.previous());

	}
}

 

By | 2012-09-18T13:40:47+00:00 September 18th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment