View RSS Feed

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 06:55 AM (504 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;
    LinkedList linkedLst = new LinkedList(); 
    ArrayList  arrayLst = new ArrayList();
    for (int m =0; m!= len; m++) {
      int x = (int)Math.random();
      linkedLst.add(x);
      arrayLst.add(x);
    }
    
    long t = System.currentTimeMillis();
    for (int i = 0; i!=len; i++) {
      linkedLst.get(i);
    }
    t = System.currentTimeMillis() - t;
    System.out.println("LinkedList -- get(index) takes "+t +"(ms)");

    t = System.currentTimeMillis();
    for  (Iterator itr = linkedLst.iterator();
      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:

LinkedList -- get(index) takes 25777(ms)
LinkedList -- Iterator takes 0(ms)
ArrayList -- get(index) takes 10(ms)
ArrayList -- Iterator takes 10(ms)

Submit "What is the advantage of using an Iterator compared to the get(index) method?" to Facebook Submit "What is the advantage of using an Iterator compared to the get(index) method?" to Digg Submit "What is the advantage of using an Iterator compared to the get(index) method?" to del.icio.us Submit "What is the advantage of using an Iterator compared to the get(index) method?" to StumbleUpon Submit "What is the advantage of using an Iterator compared to the get(index) method?" to Google

Categories
Linked List

Comments