Java arraylist iterator example

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IterateElementsUsingIterator {

	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);

		/*
		 * iterator() method in list would returns an iterator over the elements
		 * in given list in proper sequence.
		 */
		Iterator<Integer> iter = list.iterator();

		System.out.println("Elements in List");

		/*
		 * hasNext() method returns true if the iteration has more elements. and
		 * would return an element rather than throwing an exception.
		 */
		while (iter.hasNext()) {
			/*
			 * next() method returns the next element in the iteration.
			 */
			System.out.println(iter.next());
		}

	}
}

 

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

About the Author:

Leave A Comment