The difference between Java set frame 05--arraylist and LinkedList

Source: Internet
Author: User

This article is the main original article, reproduced please specify the source: http://blog.csdn.net/eson_15/article/details/51145788


The previous study has finished the list part of the source code, mainly ArrayList and LinkedList two parts of the content, this section mainly summarizes the contents of the list section. List Overview

Let's take a look at the list in the collection frame chart:


From the diagram we can see that:

1. List is an interface that inherits from the collection interface and represents an ordered queue.

2. Abstractlist is an abstract class that inherits from Abstractcollection. Abstractlist implements methods other than size (), get (int location) in the list interface.

3. Abstractsequentiallist is an abstract class that inherits from Abstrctlist. Abstractsequentiallist implements the "All methods of the list, which manipulate the list according to the index value."

4. ArrayList, LinkedList, vector, and stack are the four implementation classes in the list, where the vector is based on JDK1.0, although it achieves synchronization, but is inefficient and no longer used, stack inheritance and vector, so don't repeat.

5. LinkedList is a two-way linked list that can also be used as a stack, queue, or two-terminal queue.

The difference between ArrayList and LinkedList
We know that in general, the difference between ArrayList and LinkedList has the following points:

1. ArrayList is a data structure based on dynamic array , and LinkedList is based on the data structure of the linked list ;

2. For random access to get and set,arraylist is better than LinkedList, because linkedlist to move the pointer;

3. For adding and removing operations Add and remove, people generally say linkedlist is faster than ArrayList, because ArrayList to move the data. But this is not the case, for add or delete, LinkedList and ArrayList does not specify who fast who slow , the following will be analyzed in detail.

We combine the previous analysis of the source code, to see why this is:

ArrayList in the random access, add and delete part of the source code is as follows:

Gets the element value of the index position public E get (int index) {rangecheck (index);///First judge whether the range of index is legal return Elementdata (index);}

    Sets the value of the index position to element and returns the original value public E set (int index, E element) {Rangecheck (index);
    E OldValue = elementdata (index);
    Elementdata[index] = element;
return oldValue;

///Add element to ArrayList at the specified location public void Add (int index, E element) {    rangecheckforadd (index);
    ensurecapacityinternal (size + 1); //increments modcount!!     //the data after index and index to the position of index+1, and then a     system.arraycopy is moved backwards from index. Elementdata, index, Elementdata, index + 1,                  
     Size-index);     elementdata[index] = element;
Then insert element     size++; at index

//Delete the element public E remove (int index) {    rangecheck (index) at the ArrayList specified location;
    modCount++;    &NBsp

E OldValue = elementdata (index);
    int nummoved = size-index-1;     if (nummoved > 0)         //left one, index position the original data has been covered by    & nbsp;    system.arraycopy (Elementdata, index+1, Elementdata, index,       
                  nummoved);     //the last one to eliminate     elementdata[--size] = null;
Clear to let GC does its work     return OldValue;
 }
LinkedList in the random access, add and delete part of the source code is as follows:

//gets the value of index node public E get (int index) {checkelementindex (index);
Return node (index). Item;
	//Set the value of index element public E set (int index, E element) {Checkelementindex (index);
	Node<e> x = node (index);
	E oldval = X.item;
	X.item = element;
return oldval;

	Add a new node public void Add (int index, E element) {Checkpositionindex (index) before the index node;
	if (index = = size) linklast (element);
else Linkbefore (element, node (index));
	//Delete index node public E remove (int index) {checkelementindex (index);
Return unlink (node (index));
	node<e> node (int index) {//Assert Iselementindex (index) at index;
		When INDEX<SIZE/2, start looking for if (Index < (size >> 1)) {node<e> x = first;
		for (int i = 0; i < index; i++) x = X.next;
	return x;
		else {//INDEX>=SIZE/2, start looking for node<e> x = last;
		for (int i = size-1 i > index; i--) x = X.prev;
	return x; }
}
As you can see from the source, ArrayList wants the element of Get (int index) to return directly to the element at the index position, and LinkedList needs to find it through a for loop, although LinkedList has optimized the lookup method, such as index < SIZE/2, the search starts on the left, but it is slower than the ArrayList to start looking from the right. There is no doubt about this.
ArrayList want to insert or delete an element at a specified location, the main time consuming is the system.arraycopy action, which moves all the elements behind the index; the LinkedList master is time-consuming to find the index through a for loop and then insert or delete it directly. This leads to the two not necessarily who fast who is slow, the following through a test program to test the speed of both insertion:

Import java.util.ArrayList;  
Import java.util.Collections;  
Import java.util.LinkedList;  
Import java.util.List; * * @description Test the efficiency of ArrayList and LinkedList inserts * @eson_15/public class Arrayorlinked {static List<inte  
    Ger> array=new arraylist<integer> ();  
  
    Static list<integer> linked=new linkedlist<integer> ();  
            public static void Main (string[] args) {//First insert 10,000 data for both (int i=0;i<10000;i++) {  
            Array.add (i);  
        Linked.add (i);  
        SYSTEM.OUT.PRINTLN ("Array Time:" +gettime (array)) for both random access;  
        SYSTEM.OUT.PRINTLN ("Linked Time:" +gettime (linked));  
        Get the time to insert the data System.out.println ("Array insert time:" +inserttime (array));  
  
    SYSTEM.OUT.PRINTLN ("Linked Insert time:" +inserttime (linked));  
        public static long GetTime (list<integer> List) {long time=system.currenttimemillis (); for (int i = 0; I &Lt 10000;  
            i++) {int index = Collections.binarysearch (list, list.get (i));  
            if (index!= i) {System.out.println ("error!");  
    } return System.currenttimemillis ()-time; }//Insert data public static long Inserttime (list<integer> List) {* * * The amount of data inserted and the position of insertion are the key aspects of both performance , * We can test the performance of both by modifying these two data/long num = 10000; Represents the amount of data to insert int index = 1000;  
        Indicates from which position the long time=system.currenttimemillis () is inserted;     
        for (int i = 1; i < num; i++) {List.add (index, i);  
          
    Return System.currenttimemillis ()-time;   }  
  
}
There are two main factors that determine their efficiency, the amount of data inserted and the position of insertion. We can change these two factors in the program to test their efficiency.

When the amount of data is small, the test program, about less than 30 of the time, the two efficiency is similar, there is no significant difference; when the volume of data is large, about 1/10 of the capacity began, linkedlist efficiency is not arraylist efficient, especially to half and the second half of the position when inserted, LinkedList efficiency is obviously lower than ArrayList, and the larger the amount of data, the more obvious. For example, I tested a situation where the insertion of 10,000 data in the index=1000 position (1/10 of the capacity) and the insertion of 10,000 data at the location of the index=5000 and in index=9000 was as follows:

Insert result in index=1000:
array time:4
linked time:240
array insert time:20
linked insert time:18

at index = 5000 Insert Result:
array time:4
linked time:229
array insert time:13
linked insert time:90

in index= 9000 Insert Result:
array time:4
linked time:237
array insert time:7
linked insert time:92
From the operation result, the efficiency of LinkedList is getting worse.

So when the amount of data inserted is very small, the difference between the two is not too large, when the amount of data inserted, about 1/10 of the capacity, before the LinkedList will be better than ArrayList, after the inferior and ArrayList, and the closer to the back of the worse. So personally think, the general preferred to use ArrayList, because LinkedList can realize the stack, queue and two-terminal queue data structure, so when the specific need, use LinkedList, of course, the small amount of data, the two are similar, depending on the specific circumstances to choose to use When the data volume is large, if only need to insert or delete the data in the front part, that also may choose LinkedList, conversely chooses the ArrayList instead the efficiency is higher.

About ArrayList and LinkedList comparison, discuss so much, if there is a mistake, please comment ~

___________________________________________________________________________________________________________ __________________________________________

-----are willing to share and make progress together.
-----More articles Please see: http://blog.csdn.net/eson_15

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.