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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.