/* Programmer : Dandy A. Macaubos
Program name : Iterators
Date Started : March 2,2009
Date Finished : March 2,2009
Purpose : Iterate through elements Java ArrayList using Iterator
Instructor : Dony Dongiapon
Subject : IT134
*/
import java.util.ArrayList;
import java.util.Iterator;
public class IterateThroughArrayListUsingIterator {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
//get an Iterator object for ArrayList using iterator() method.
Iterator itr = arrayList.iterator();
//use hasNext() and next() methods of Iterator to iterate through the elements
System.out.println("Iterating through ArrayList elements...");
while(itr.hasNext())
System.out.println(itr.next());
}
}
/*
Output would be
Iterating through ArrayList elements...
1
2
3
4
5
*/
/*source : http://www.java-examples.com/iterate-through-elements-java-arraylist-using-iterator-example
What I did I learned in this topic?
I learned that before you can access a collection through an iterator, you must obtain one.
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.
*/
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment