ArrayList and LinkedList differences in Java

Source: Internet
Author: User

Generally everyone knows the general difference between ArrayList and LinkedList:
1.ArrayList is a data structure based on dynamic array , LinkedList data structure based on linked list .
2. for random access get and set. ArrayList thinks better than LinkedList, because LinkedList wants to move the pointer.


3. for new and deleted operations the add and remove,linedlist are more dominant , because ArrayList to move the data.

4.ArrayList: Random access, sequential storage. LinkedList: Sequential interview, random storage;

ArrayList and LinkedList are two collection classes that store a series of object references (references). For example, we can use ArrayList to store a series of string or integer.

So what's the difference between ArrayList and LinkedList in performance? When should I use ArrayList when should I use LinkedList?


A. Complexity of Time
First of all, the key point is. The internal implementation of ArrayList is based on the underlying object array, so. It uses the Get method to access a random element in the list (random access), which is faster than LinkedList. The Get method in LinkedList is checked sequentially from one end of the list to the other end. For LinkedList. There is no faster way to access a specified element in the list.


If we have a very large list, the elements inside it are already lined up. This list may be of type ArrayList or LinkedList type, now we are looking at this list for binary search, the comparison list is ArrayList and LinkedList when the query speed, see the following program:

Package Com.story.test;import java.util.LinkedList; Import java.util.List; Import Java.util.Random; Import java.util.ArrayList; Import Java.util.Arrays; Import java.util.Collections;     public class testlist{public static final int times = 50000;         public static List values;         static{Integer vals[]=new Integer[times];         Random r=new random ();            for (int i=0,currval=0;i < times;i++) {Vals[i] = new Integer (currval);         Currval + = r.nextint (100) +1;     } values = Arrays.aslist (Vals);    } Static Long Timelist (List lst) {Long start = System.currenttimemillis ();    for (int i = 0;i < times;i++) {int index = Collections.binarysearch (LST, Values.get (i));    if (Index! = i) {System.out.println ("* * * * * * * * * *");    }} return System.currenttimemillis ()-start;        public static void Main (String args[]) {System.out.println ("ArrayList Consumption Time:" +timelist (new ArrayList (values)); System.out.println ("LinkedList Consumption time:+timelist (new LinkedList (values)); }        }


The output I get is:

ArrayList consumption time: 11
LinkedList consumption time: 5665


This result is not fixed, but basically ArrayList time is obviously less than linkedlist time. Therefore, it is not advisable to use linkedlist under such circumstances.

The binary lookup method uses the random access policy. The LinkedList is not supported by high-speed random access. The time spent on a random interview with a linkedlist is proportional to the size of the list.

The time spent on random access in ArrayList is fixed.
Does this mean that ArrayList is always better than linkedlist performance? This does not necessarily mean that in some cases the performance of LinkedList is better than that of ArrayList, and some algorithms are more efficient when implemented in LinkedList.

Say, for example. When the list is reversed using the Collections.reverse method. Its performance will be better.
looking at this example, adding that we have a list to do a lot of insertions and deletions, in which case LinkedList is a better choice. Consider an example of an extreme, where we repeatedly insert an element at the beginning of a list:

Package Com.story.test;import java.util.*; public class Listtest {static final int times = 50000;static long timelist (list list) {Long Start=system.currenttimemillis ( );    Object o = new Object ();    for (int i=0; i < times; i++) {    list.add (0,o);    }    Return System.currenttimemillis ()-start;} public static void Main (string[] args) {System.out.println ("ArrayList Time:" +timelist (New ArrayList ()));         System.out.println ("LinkedList Time:" +timelist (New LinkedList ())); }}


The result of my output is:

ArrayList time: 264
LinkedList Time: 7


This is in contrast to the result of the previous example, when an element is added to the beginning of ArrayList, all existing elements are moved back, which means the overhead of data movement and replication.

On the contrary. Adding an element to the beginning of the LinkedList is simply not an element that is assigned a record. Then adjust the two connections.

The overhead of adding an element at the beginning of LinkedList is fixed, and the cost of adding an element at the beginning of ArrayList is proportional to the size of the ArrayList.


two. Complexity of Space
In LinkedList there is a private inner class, which defines such as the following:

private static class Entry {    Object element;    Entry Next;    Entry previous;}


Each entry object reference an element in the list, and at the same time has its previous element and the next element in LinkedList.

A LinkedList object with 1000 elements will have 1000 entry objects that are linked together. Each object corresponds to an element in the list. In this case, there will be a very large space overhead in a linkedlist structure, because it stores information about the 1000 entity objects.


ArrayList uses a built-in array to store elements, and the starting capacity of this array is 10. When the array needs to grow, the new capacity is obtained by, for example, the following formula: the new capacity = (old capacity)/2+1, which means that each capacity will probably increase by 50%. This means that if you have a ArrayList object that includes a large number of elements, then eventually there will be a lot of wasted space, and this waste is caused by the way ArrayList works itself.

Suppose there is not enough space to hold the new element. The array will have to be allocated again in order to be able to add new elements. Another allocation of an array will result in a dramatic decrease in performance. Suppose we know how many elements a ArrayList will have, and we can specify the capacity by constructing the method.

We are also able to remove wasted space after the ArrayList allocation is completed by the TrimToSize method.


three. Summary
ArrayList and LinkedList have advantages and disadvantages in performance. All have their own place of application, and in general can describe the narrative as follows:
1. For ArrayList and LinkedList, the overhead of adding an element at the end of a list is fixed.

For ArrayList, the main point is to add an entry in the internal array, pointing to the element being added, which may occasionally cause the array to be allocated again, while for LinkedList. This overhead is uniform. Assigns an internal entry object.

2. Inserting or deleting an element in the middle of a ArrayList means that the remaining elements in the list will be moved, while the overhead of inserting or deleting an element in the middle of the linkedlist is fixed.

3. LinkedList does not support efficient random element access.

4. ArrayList's space waste the main body now reserves a certain amount of space at the end of the list, while the LinkedList's space costs each of its elements now consumes considerable space.


It is possible to say that using ArrayList provides better performance when the operation is to add data to a column of data rather than in front or in the middle, and to randomly access elements in it. You should use LinkedList when you are adding or deleting data in front of or in the middle of a column of data, and when you follow the elements in a sequential way.


ArrayList and LinkedList differences in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.