Answer:
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
Now, the running time for copyOf() function is O(N) where N is the size/capacity of the ArrayList. Hence, the time complexity of trimToSize() function is O(N).
Hence, the running time of building an N-item ArrayList is O(N^2).
Please find the sample code below.
CODE
==================
import java.util.ArrayList;
public class Driver {
public static void main(String[] args) throws Exception{
int N = 100000;
ArrayList<Integer> arr = new ArrayList<>(N);
long startTime = System.currentTimeMillis();
for(int i=0; i<N; i++) {
arr.add(i);
arr.trimToSize();
}
long endTime = System.currentTimeMillis();
double time = (endTime - startTime)/1000;
System.out.println("Total time taken = " + time + " seconds.");
}
}
Explanation: