为什么将元素添加到链表的时间更长(Java)

时间:2019-03-03 17:54:21

标签: java data-structures time-complexity

当我运行以下代码时

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变慢?

0 个答案:

没有答案