Implementation details for the Java collection--arraylist and LinkedList

Source: Internet
Author: User
Tags array length prev

ArrayList and LinkedList differences in implementation

The list represents a linear table of data structure, ArrayList is a sequential storage of the linear table, ArrayList in the form of dynamic array to save each set element, LinkedList is a chain-stored linear table, which is essentially a doubly linked list, It not only implements the list interface, but also implements the Deque interface, Deque represents a two-terminal queue, both the queue (FIFO) characteristics, but also has the characteristics of the stack (FILO), that is, LinkedList can be used as a doubly linked list, but also as a queue to use, It can also be used as a stack.

 Public class Linkedlist<e>extends abstractsequentiallist<e>implements List<e>, deque<e , Cloneable, java.io.Serializable

The ArrayList bottom uses a elementdata array to hold all the collection elements, so ArrayList needs to do two things when inserting an element:

①, save ArrayList The array length of the underlying package is greater than the number of collection elements

②, moves all array elements after the insertion position "move whole", moving backward One "lattice"

When you delete an element at a specified position in the ArrayList collection, the program also takes a "whole move", and the array element at the deleted index is also assigned a value of NULL, and the following is the source code for the Remove (int index) method of the ArrayList collection.

 public  E Remove (int   index) {Rangecheck (index);        Modcount  ++;        E oldValue  = Elementdata (index);         int  nummoved = Size-index-1;  if  (nummoved > 0 +1, Elementdata, index, nummoved); elementdata[--size] = null ; //         clear to let GC do it work  return      OldValue; }

For ArrayList collections, when a program adds or deletes a collection element to a ArrayList, the ArrayList bottom layer requires an "overall move" of the array, so performance is poor.

However, if the program calls the Get (int index) method to remove elements from the ArrayList collection, the performance and array are almost identical and efficient. The following is the source code for the Get (int index) method of the ArrayList collection.

  e elementdata (int  index) {       return  (E) elementdata[index];  }         Public E get (int  index) {        Rangecheck (index);         return Elementdata (index);    }    

LinkedList is essentially a doubly linked list, so it uses an inner class to hold each set element.

 private  static  class  node<e> {
//collection element E item;
Save a reference to the next linked list node node <e> Next;
//Save a reference to the previous linked list node node <e>       prev; Common constructor Node (node <E> prev, E element, Node<e> next) { this . Item = element; this . Next = next; this . Prev = prev; } }

From the bold code in the above program, it can be seen that a node object represents a nodes of a doubly linked list, the next variable in the object points to the next node, the previous child points to the previous node.

Since LinkedList uses a doubly linked list to hold the collection elements, it adds the collection elements as long as the list is inserted. Here is the source code for the LinkedList add node.

      Public void Add (int  Index, E Element) {        Checkpositionindex (index);         if (Index = = size)            linklast (Element)        ; Else             Linkbefore (element, node (index));    }

As seen from the above code, since linked is essentially a doubly linked list, it is very convenient to insert a new node before the specified node.

The following three methods are used in the add (int index,e Element) method implementation.

①, node (int index): Searches for the specified index-out element

②, Linklast (e E): Inserting the new E-node into the last

③, Linkbefore (E e,node<e> succ): Insert E new node before SUCC node

Node (int index) is actually the underlying implementation of the get (int index) method. Linked must search through the elements until the index element is found. Node (int index) is searched by dichotomy, and the following is the source code for the method.

Node<e> node (intindex) {        //assert Iselementindex (index);If index is less than SIZE/2if(Index < (size >> 1) ) {Node<E> x =First ;  for(inti = 0; I < index; i++) x=X.next; returnx; } Else{Node<E> x =Last ;  for(inti = size-1; i > Index; i--) x=X.prev; returnx; }    }

The above node (int index) method is to find element by element, but because LinkedList is a doubly linked list, so the program first according to the value of index to determine whether it is close to the linked list or close to the end of the chain, if the end of the chain table near the beginning of the search, If close to the end of the list, search from the end of the end.

The Get (int index) method of linked is simply a wrapper over the node (int index) method above. The source code for the Get (int index) method is as follows.

     Public E get (int  index) {        checkelementindex (index);         return node (index). Item;    }

However, the simple insert operation is simpler, as long as you modify the previous within a few nodes, next reference value can be. The following is the source code for the Linkedbefore (E-E, node<e> succ) method.

   voidLinkbefore (e E, node<e>succ) {        //assert succ! = null;        Finalnode<e> pred =Succ.prev; FinalNode<e> NewNode =NewNode<>(Pred, E, succ); Succ.prev=NewNode; if(Pred = =NULL) First=NewNode; ElsePred.next=NewNode; Size++; Modcount++; }

If you simply add a node, then the performance of LinkedList is very good, but if you need to add a node to a specified index, LinkedList must first find the node at the specified index, the system overhead of the search process is not small, Therefore, the performance of the LinkedList add (int index,e E) method is not particularly good. Performance is very good if only LinkedList addfrist (e E), AddLast (e E), Offerfrist (E), Offerlast (E), Pollfrist (E), Polllast (e e) are used. Because the search process can be avoided.

Similarly, in order to implement the Remove (int index) method, LinkedList must first find the node at the index index through node (int index), then modify the next reference to its previous node, and the previous reference to the latter node. The following is the source code for the method.

     PublicE Remove (intindex)        {Checkelementindex (index); returnUnlink (node (index)); } E unlink (Node<E>x) {//assert x! = null;        FinalE element =X.item; FinalNode<e> next =X.next; FinalNode<e> prev =X.prev; if(prev = =NULL) { First=Next; } Else{Prev.next=Next; X.prev=NULL; }        if(Next = =NULL) { last=prev; } Else{Next.prev=prev; X.next=NULL; } X.item=NULL; Size--; Modcount++; returnelement; }

To sum up, ArrayList, LinkedList have their own scenarios, most of the time, ArrayList performance is always better than linkedlist, so most should consider the use of ArrayList collection. However, if the program Jing Chu needs to add, delete elements, especially often need to add (e) method to the collection of elements, you should consider using the LinkedList collection.

Implementation details for the Java collection--arraylist and LinkedList

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.