190k views
5 votes
Suppose list1 is an ArrayList and list2 is a LinkedList. Both contains 1 million double values. Analyze the following code: A: for (int i = 0; i < list1.size(); i++) sum += list1.get(i); B: for (int i = 0; i < list2.size(); i++) sum += list2.get(i);

1 Answer

2 votes

Answer:

Code A runs faster than Code B.

Step-by-step explanation:

Values are stored as index based in the ArrayList. If you like to access one element, time complexity will be O(1). However, if you like to access an element in the LinkedList, you need to go through all the elements before that element, time complexity will be O(n).

User Scarlett
by
7.6k points