Iterator:
- It is an interface.
- Iterator providing methods to iterator any collection.
- iterator() method returns Iterator object of any collection.
Methods:
- boolean hasNext(): checks the next element is present or not to iterate.
- Object next(): returns the next element of iterator object.
Program to display ArrayList using Iterator:
import java.util.*; class Code { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for(int i=1 ; i<=5 ; i++) list.add(i*5); System.out.println(“Display using Iterator :”); Iterator<Integer> itr = list.iterator(); while(itr.hasNext()) { Integer ele = itr.next(); System.out.println(ele); } } } |
When we use for/for-each/iterator?
For-loop | For-each loop | Iterator |
Index based. | Not index based. | Not index based. |
Process only List(index based) | Process List, Set and Map | Process List, Set and Map |
Use get(index) method | Do not use any other method | Do not use any other method |