0
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

    public class Sample {

        Calendar cal = Calendar.getInstance();


        void getData(ArrayList<InvoiceBillingProjects> projectDataList){
            //System.out.println("start");
            long start = System.nanoTime();
            Iterator<InvoiceBillingProjects> itr = projectDataList.iterator();

            while(itr.hasNext()){
            //  InvoiceBillingProjects ibpp = itr.next();
                itr.next().getDescription();
            }
            /*for(int i=0;i<projectDataList.size();i++){
                projectDataList.get(i).getDescription();
            }*/
            long end = System.nanoTime();
            System.out.println(" time "+(end-start));
        }


        public static void main(String arg[]) {

            ArrayList<InvoiceBillingProjects> projectDataList = new ArrayList<InvoiceBillingProjects>();
            List<InvAssociateDetails> lt = new LinkedList<InvAssociateDetails>();
            for(int i=0;i<120000;i++){
                 lt.add(new InvAssociateDetails());
                //new InvoiceBillingProjects().setAssociateList(lt);

            }
            for(int i=0;i<120000;i++){
                InvoiceBillingProjects ibp = new InvoiceBillingProjects();
                projectDataList.add(ibp);
                ibp.setAssociateList(lt);
            }

            new Sample().getData(projectDataList);
        }
    }

The search across the list should be faster when using an iterator than a for loop. The above program shows more time elapsed between the start and end of the iteration. Why does using an iterator take more time?

Jacob
  • 1,560
  • 4
  • 19
  • 41
Akhil Gupta
  • 265
  • 1
  • 14

1 Answers1

0

What was the difference in time? The two should be about the same. Remember that looking up an element in an ArrayList is constant-time (O(1)). Both methods of iteration use that same lookup.

  • Thanks ArthuruhtrA, I got it since the time result I was expecting will be the case if I use Implementation of List as LinkedList and NOT Array List. My Bad :) – Akhil Gupta Aug 12 '16 at 04:15