# Algorithm and Data Structure

#### What is the advantage of using an Iterator compared to the get(index) method?

###### Rate this Entry
by , 02-19-2012 at 07:55 AM (423 Views)
One of the following methods should be used to iterate the List.

1. Iterator
2. get(index)

get(index) method is quite slower in comparison with Iterator.

Consider this example:

Java Code: This is the code to explain Iterator
```public class TestClass {
public static void main(String[] args) {
int  len = 100000;
ArrayList  arrayLst = new ArrayList();
for (int m =0; m!= len; m++) {
int x = (int)Math.random();
}

long t = System.currentTimeMillis();
for (int i = 0; i!=len; i++) {
}
t = System.currentTimeMillis() - t;
System.out.println("LinkedList -- get(index) takes "+t +"(ms)");

t = System.currentTimeMillis();
itr.hasNext();) {
itr.next();
}
t = System.currentTimeMillis() - t;
System.out.println("LinkedList -- Iterator takes "+t +"(ms)");

t = System.currentTimeMillis();
for (int i = 0; i!=len; i++) {
arrayLst.get(i);
}
t = System.currentTimeMillis() - t;
System.out.println("ArrayList -- get(index) takes "+t +"(ms)");

t = System.currentTimeMillis();
for  (Iterator itr = arrayLst.iterator();
itr.hasNext();) {
itr.next();
}
t = System.currentTimeMillis() - t;
System.out.println("ArrayList -- Iterator takes "+t +"(ms)");

}
}```
Output: