I make a testing like this:
int target = 100000000;
ArrayList<Integer> arrayList = new ArrayList<>();
int[] array = new int[target];
int current;
long start, getArrayListTime, getArrayTime;
for (int i = 0; i < target; i++) {
arrayList.add(i);
array[i] = i;
}
start = System.currentTimeMillis();
for (int i = 0; i < target; i++) {
current = arrayList.get(i);
}
getArrayListTime = System.currentTimeMillis() - start;
start = System.currentTimeMillis();
for (int i = 0; i < target; i++) {
current = array[i];
}
getArrayTime = System.currentTimeMillis() - start;
System.out.println("get arrayList time: " + getArrayListTime + "ms, get array time: " + getArrayTime + "ms");
After I execute this code, the console show:
get arrayList time: 143ms, get array time: 2ms
I know that when add element to ArrayList but it have not more space to add it, it will allocate a 1.5x capacity array and copy origin array element to newest array, so it need additional time to process it.
But why I access ArrayList element, it have to spend more time than array? isn't it all both a continuous block in memory?