Iterator : hasNext() and next()

Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. In general, to use an iterator to cycle through the contents of a collection, follow these steps:

Call the collection’s iterator() method

Create a loop that calls the hasNext() — which returns a boolean variable. If the returned variable is true, the iterator object accesses the collection; otherwise the looping stops.

Call the next() method to obtain each item of the collection.

Program

0

 

 

 

Program Source

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

public class Javaapp {

    public static void main(String[] args) {
        
        ArrayList array1 = new ArrayList();
        array1.add(10);
        array1.add(30);
        array1.add(40);
        array1.add(55);
        array1.add(60);
        System.out.println("array1 : "+array1);
        
        Iterator itr = array1.iterator();
        while(itr.hasNext())
        {
            System.out.println(itr.next());
        }
    }
}

Leave a Comment