Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java Program used to iterate the elements in the arraylist and display using iterator() method

BACK

Iterator program to iterate the elements in the arraylist and display

Example Program

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

public class Iterater {
	public static void main(String[] args) {
		ArrayList<String> al = new ArrayList<String>();
		// add elements to the array list
		al.add("C");
		al.add("A");
		al.add("E");
		al.add("B");
		al.add("D");
		al.add("F");

		// Use iterator to display contents of al
		System.out.print("Original contents of al: " + al);
		Iterator<String> itr = al.iterator();
		while (itr.hasNext()) {
			Object element = itr.next();
			System.out.print(" " + element);
		}

	}

}


Output

Original contents of al:


C A E B D F

Description

An Iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.

Declaration

Iterator<E> iterator()

Parameters

E – the type of elements returned by this iterator

Return Value

String

Exception

NoSuchElementException – if the iteration has no more elements

UnSupportedOperationException – if the remove operation is not supported by this iterator

IllegalStateException-  if the next method has not yet been called, or the remove method has already been called after the last call to the next method


BACK

Related Posts:

  • List Iterator example program is to iterate the elements in…
  • ArrayList example programs and Tutorial in java
  • Iterate LinkedHashSet elements using Iterator iterator()
  • HashSet example program for Iterator iterator()
  • Iterate Treeset elements using Iterator iterator()


This post first appeared on Core Java,Servlet,Jsp,Struts,Hibernate,Spring Fram, please read the originial post: here

Share the post

Java Program used to iterate the elements in the arraylist and display using iterator() method

×

Subscribe to Core Java,servlet,jsp,struts,hibernate,spring Fram

Get updates delivered right to your inbox!

Thank you for your subscription

×