I was given the following little multiple-choice question in my APCS class concerning adding elements to ArrayList's and although one particular answer seems intuitively correct to me (choice B), I'm not entirely sure whether it's indeed right or what's actually going on behind the scenes performance-wise:
//Consider the following methods
public static List<Integer> process1(int n) {
List<Integer> someList = new ArrayList<Integer>();
for (int k = 0; k < n; k++) {
someList.add(new Integer(k));
}
return someList;
}
public static List<Integer> process2(int n) {
List<Integer> someList = new ArrayList<Integer>();
for (int k = 0; k < n; k++) {
someList.add(k, new Integer(k));
}
return someList;
}
//Which of the following best describes the behavior of process1 and process2?
//(A) Both methods produce the same result and take the same amount of time
//(B) Both methods produce the same result and process1 is faster than process2
//(C) The two methods produce different results and process1 is faster than process2
//(D) The two methods produce different results and process2 is faster than process1
Note: I did test both methods out on my computer using large enough parameters and both are quite close in run length, but method1 seems to be slightly faster. Also, this isn't a homework problem to be turned in or anything, so no need to feel worried about providing me with answers:)
process2method you want to test withsomeList.add(0, new Integer(k));instead ofsomeList.add(k, new Integer(k));. Then you might notice a difference. Becauseadd(int, element)willshifts the element currently at that position (if any) and any subsequent elements to the right. This would be O(n) in my view. With the current code you always adding the element into the next element that is available and I think that is why the performance numbers are same for both methods. Where asadd(element)has O(1) complexity.