当我运行以下代码时
public class Test {
public static void main(String[] args) {
List<Integer> linkedList = new LinkedList<>();
long linkedListTimeStart = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
linkedList.add(i);
}
long linkedListTimeEnd = System.currentTimeMillis() - linkedListTimeStart;
System.out.println("Linkedlist took: " + linkedListTimeEnd);
//-------------------------ARRAYLIST--------------------------------///
List<Integer> arrayList = new ArrayList<>();
long arrayListTimeStart = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
arrayList.add(i);
}
long arrayListTimeEnd = System.currentTimeMillis() - arrayListTimeStart;
System.out.println("ArrayList took: " + arrayListTimeEnd);
}
}
我得到输出:
Linkedlist took: 165
ArrayList took: 87
如果我错了,现在纠正我,但是将元素添加到LinkedList不需要花费固定的时间,而将O(n)添加到ArrayList需要花费时间吗?如果是这样,为什么LinkedList变慢?