ArrayList and LinkedList differences in Java

Source: Internet
Author: User

Generally everyone knows the general difference between ArrayList and LinkedList:
1.ArrayList is the realization of the data structure based on dynamic array, LinkedList data structure based on linked list.
2. For random access get and set,arraylist feel better than LinkedList, because linkedlist to move the pointer.
3. Add and Remove,linedlist are the dominant for new and deleted operations because ArrayList is moving the data.


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 in performance between ArrayList and LinkedList? When should I use ArrayList when should I use LinkedList?

one. Time complexity  
The first point is that the internal implementation of ArrayList is based on an array of objects, so when it uses the Get method to access any one of the elements in the list (random access), It's faster than LinkedList. The Get method in LinkedList is checked from one end of the list in order until the other end. For LinkedList, there is no faster way to access a specified element in the list.  
Let's say we have a large list of elements that are already sorted, the list may be of type ArrayList or LinkedList, and now we're going to look at this list for binary search. The comparison list is ArrayList and LinkedList when the query speed, see the following program:  

Package com.mangocity.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 n=50000;          public static List values; Static ...              {Integer vals[]=new integer[n];              Random r=new random (); for (int i=0,currval=0;i<n;i++) ...                {vals=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<n;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));    }   }

I get the output is: ArrayList consumption time: 15 
                  LinkedList consumption time: 2596 
This result is not fixed, but basically ArrayList time is significantly less than linkedlist time. Therefore, it is not advisable to use LinkedList in this case. The binary lookup method uses the random access policy, while LinkedList is not supported for fast random access. The amount of time spent on a random access to a linkedlist is proportional to the size of the list. Accordingly, the time spent in 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. For example, if you use the Collections.reverse method to invert a list, its performance will be better.  
Look at an example, join us there is a list, to do a lot of insertions and deletions, in this case LinkedList is a good choice. Consider the following extreme example, where we repeatedly insert an element at the beginning of a list:  

Package com.mangocity.test;     Import java.util.*;   public class Listdemo {        static final int n=50000;        Static long Timelist (list list) {        long start=system.currenttimemillis ();        Object o = new Object ();        for (int i=0;i<n;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 ()));        }   }   

At this point my output is: ArrayList time: 2463

LinkedList Time: 15
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. Conversely, adding an element to the beginning of LinkedList is simply not an element that allocates a record and then adjusts two connections. The overhead of adding an element at the beginning of the LinkedList is fixed, while the overhead of adding an element at the beginning of ArrayList is proportional to the size of the ArrayList.

two. Complexity of Space
There is a private inner class in LinkedList, which is defined as follows:

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

  

Each entry object reference an element in the list, along with its previous element and the next element in LinkedList. A LinkedList object with 1000 elements will have 1000 entry objects linked together, each of which corresponds to an element in the list. In this case, there will be a significant 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 as follows: 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 with 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. If there is not enough space to hold the new element, the array will have to be reassigned so that new elements can be added. Redistribution of the array will result in a dramatic decrease in performance. If we know how many elements a ArrayList will have, we can construct a method to specify the capacity. We can also remove wasted space after the ArrayList is allocated through the TrimToSize method.


Three Summarize
ArrayList and LinkedList have their own advantages and disadvantages in performance, and each has its own applicable place, which can be described as follows:
1. For ArrayList and LinkedList, the overhead of adding an element at the end of the 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 redistributed, whereas for LinkedList, the overhead is uniform, allocating 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 space waste is mainly reflected in the end of the list to reserve a certain amount of space, and the space cost of LinkedList is reflected in its every element needs to consume considerable space


It can be said that using ArrayList provides better performance when the action is to add data after a column of data rather than in front or in the middle, and to randomly access its elements, and when your action is to add or delete data in front or in the middle of a column of data, and to access its elements sequentially, You should use the LinkedList.

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.