Programmer: Cuming Mary Grace
Program name: Arraylist(Iterator)
Date Started:MArch 2,2009
Date Finished: MArch 11, 2009
Purpose of the programm: To know more about Iterator
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class IteratorSample {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList(); // this create an Arraylist for the Animal
arrayList.add("cat"); //it Add elements to Arraylist
arrayList.add("dog");
arrayList.add("rat");
arrayList.add("bat");
arrayList.add("bug");
//in order to get the object in the arraylist we used the Iterator() method.
ListIterator itr = arrayList.listIterator();
//use hasNext() which Returns true if the iteration has more elements
//and next()method which Returns the next element in the iteration in order to iterate through the elements
System.out.println("Animal ArrayList elements...");
while(itr.hasNext())
System.out.println(itr.next());
/*
Use hasPrevious() and previous() methods of ListIterator to iterate through
the elements in backward direction.
*/
System.out.println("Iterating through ArrayList elements in backward direction...");
while(itr.hasPrevious())
System.out.println(itr.previous());
}
}
No comments:
Post a Comment