Saturday, April 6, 2013

Java Iterator Example

Java Iterator Example

I am giving the very straight forward example how you Iterate the elements from the ArrayList.

Iterator is the interface which is there in the package java.util.

You can iterate the elements from the Iterator by using the methods hashNext() and next().

By using remove() method we can remove the elements from the Iterator.

Sample code for the Java Iterator Example :


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

/*
 * JavaIterator Example
 */
public class JavaIteratorExample {
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        
        //Storing the elements into the arraylist.
        ArrayList aList = new ArrayList();
        aList.add("val-1");
        aList.add("val-2");
        aList.add("val-3");
        
        //Retrieving the elements from the ArrayList by using Iterator
        Iterator iterator = aList.iterator();
        String value = "";
        while(iterator.hasNext()){
            value = (String)iterator.next();
            System.out.println(value);            
        }                
    }

}


Output :

val-1
val-2
val-3




0 comments:

Post a Comment

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.