Iterator In Java Example
Chapter:
Collections
Last Updated:
22-07-2016 07:47:15 UTC
Program:
/* ............... START ............... */
import java.util.ArrayList;
import java.util.Iterator;
public class JavaIteratorExample {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Java");
arrayList.add("C");
arrayList.add("C#");
arrayList.add("Phython");
Iterator itr = arrayList.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
System.out.println(str + " ");
}
}
}
/* ............... END ............... */
Output
Notes:
-
Iterator enables you to cycle through a collection, obtaining or removing elements.
- boolean hasNext( ) -Returns true if there are more elements. Otherwise, returns false.
- Object next( ) -Returns the next element. Throws NoSuchElementException if there is not a next element.
- void remove( ) - Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).
Tags
Collection, Iterator, Java