ArrayList Iterator Example

ArrayList Iterator Example

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

public class IteratorExample {

public static void main(String[] args) {

ArrayList<String> arr= new ArrayList<String>();

arr.add(“Shivam”);
arr.add(“Raju”);
arr.add(“Mukesh”);
arr.add(“Bela”);
Iterator<String> itr=arr.iterator();

// hasNext()
//Returns true if there are more elements. Otherwise, returns false.

while (itr.hasNext()) {

/*
* Returns the next element.
* Throws NoSuchElementException if there is not a next element
* To avoid this exception call hasNext() before next()
*/

System.out.println(“Element Is:”+itr.next());
}

}
}

Output:

Element Is:Shivam

Element Is:Raju

Element Is:Mukesh

Element Is:Bela

 

Leave a Reply

Your email address will not be published. Required fields are marked *

2 + 7 =