9:41 pm - Saturday January 21, 2017

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

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

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

Filed in: Z-A All Java Codes

Comments are closed.