Here, we will introduce about the iterator interface of java collection framwork.
Iterator in java.
An Iterator is a process of traversing through all the elements in a container or list. There is no matter in which order elements are arranged. An Iterator iterate through the elements sequentially.
Definition of an Iterator
In computer science Iterator is defined as an object that allows traversing over all the elements of collection in a sequence. It is a process of cycling through the elements in a collection. Some times in the context of database it is called a cursor.
Syntax
An Iterator object is implemented by the following two interfaces :
1. public interface Iterator<E>
2. public interface ListIterator<E>
Parameter Description
E : It is the type of elements backed by this iterator.
Example of implementation of the above both interfaces
In this example we will show you only how the above two interfaces can be implemented. You can see more example of these interfaces with their methods individually in next section. Through this example we will show you how can these interfaces are instantiated and how they iterate with their methods.
Example:-
package Devmanuals.com; import java.util.List; import java.util.ArrayList; import java.util.LinkedList; import java.util.Iterator; import java.util.ListIterator; public class IteratorAndListIterator { public static void main(String args[]) { ArrayList alist = new ArrayList(); alist.add(1); alist.add(2); alist.add(3); // Implementation of Iterator Iterator<Integer> itr = alist.iterator(); System.out.println("First element of arrayList =" +itr.next()); System.out.println("Second element of arrayList =" +itr.next()); System.out.println("Third element of arrayList =" +itr.next()); LinkedList llist = new LinkedList(); llist.add(4); llist.add(5); llist.add(6); // Implementation of ListIterator ListIterator<Integer> litr = llist.listIterator(); System.out.println("\nFirst element of linkedList =" +litr.next()); System.out.println("Second element of linkedList =" +litr.next()); System.out.println("Third element of linkedList =" +litr.next()); } }
Output :
First element of arrayList =1
|
[ 0 ] Comments