Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

data structures - Java, Adding time LinkedList vs ArrayList

just adding Integer numbers to Arraylist and Linkedlist, to the last position, why adding in arrayList is faster then the linkedlist? I compiled many many times, and adding in arraylist is faster, why?

As I know, ArrayList copies an array by 2^n+1 size. while linkedlist changes only the Node

class Test1 {

public static void main(String[] args) {
    ArrayList<Integer> arrayList = new ArrayList<>();
    LinkedList<Integer> linkedList = new LinkedList<>();

    addToList(arrayList);
    System.out.println("-----------------");
    addToList(linkedList);

}

public static void addToList(List list) {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 5_000_000; i++) {
        list.add(i);
    }
    long end = System.currentTimeMillis();
    System.out.println(end - start);

}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you add to an ArrayList, you just have to store the integer in the backing array. Every once in a while, when the backing array fills up, you have to allocate a new array and copy all the old items to the new array. Given 5 million integers, you'll have to do that allocate-and-copy about 20 times (depends on the initial size of the list).

To add to a linked list, every addition requires that you:

  1. Allocate memory for and initialize a new linked list node.
  2. Link the new node to the end of the list.

All that extra work, for both the ArrayList and the LinkedList is done behind the scenes, by the add method.

The overhead for 5 million linked list node allocations and links is higher than the overhead for 5 million ArrayList insertions, even when you count the 20 or so allocate-and-copy operations that the ArrayList has to make when it fills up.

So, whereas each operation takes constant time (although in the ArrayList case it's really amortized constant time), the constant for appending to a linked list is higher than the constant for appending to an ArrayList.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...