Java Data structure-------List

Source: Internet
Author: User
Tags assert prev

Three kinds of list:arraylist,vector,linkedlist

Class inheritance Diagram

    

ArrayList and vectors are implemented using arrays, and almost the same algorithm is used; the difference is that ArrayList is not thread-safe, and the majority of vector methods do thread synchronization.

The LinkedList is implemented through a doubly linked list.

Source Code Analysis

1. Add element to the end of the list (appends the specified element to the end of this list.)

ArrayList: When the required capacity exceeds the size of the current ArrayList, it needs to be expanded to have a certain effect on performance.

Optimization strategy: When the initial value of the ArrayList array is effectively evaluated, specifying its capacity size can help improve performance and avoid frequent expansion.

     Public BooleanAdd (e e) {ensurecapacityinternal (size+ 1);//increments modcount!! ensure that the internal array has enough spaceelementdata[size++] = e;//Place an element at the end of an array        return true; }    Private voidEnsurecapacityinternal (intmincapacity) {        if(Elementdata = =empty_elementdata) {mincapacity= Math.max (default_capacity, mincapacity);//if the array is an empty array, take the initial capacity and the maximum value in mincapacity, the initial capacity default_capacity = Ten} ensureexplicitcapacity (mincapacity); }    Private voidEnsureexplicitcapacity (intmincapacity) {Modcount++;//The number of times modified, the iterator member variable expectedmodcount is the value of the Modcount when it was created, to determine whether the list was modified during the iteration//overflow-conscious Code        if(Mincapacity-elementdata.length > 0) grow (mincapacity); //Expand if the required capacity is larger than the size of the array    }    Private voidGrowintmincapacity) {        //overflow-conscious Code        intOldcapacity =elementdata.length; intNewcapacity = oldcapacity + (oldcapacity >> 1);//1.5 times times the old capacity. Binary right shift one is almost equivalent to a decimal divided by 2, and for the CPU, the right shift is faster than the other. If the oldcapacity is an even number,newcapacity is 1.5*oldcapacity, otherwise 1.5*oldcapacity-1.         if(Newcapacity-mincapacity < 0)//if the calculated capacity is not sufficient, use the mincapacityNewcapacity =mincapacity; if(Newcapacity-max_array_size > 0)//if the calculated capacity is greater than max_array_size=integer.max_value-8,Newcapacity =hugecapacity (mincapacity); //mincapacity is usually close to size, so this is a win:Elementdata = arrays.copyof (Elementdata, newcapacity);//call the System.arraycopy method to copy an array    }   //determine if the maximum value of the array is greater than integer.max_value, question: What is the meaning of setting max_array_size=integer.max_value-8?     Private Static intHugecapacity (intmincapacity) {        if(Mincapacity < 0)//Overflow            Throw NewOutOfMemoryError (); return(Mincapacity > Max_array_size)?Integer.MAX_VALUE:MAX_ARRAY_SIZE; //}

LinkedList: Each new element requires a new node object, and more assignment operations. In frequent calls, performance can have a certain impact.

     Public BooleanAdd (e e) {linklast (e); return true; }    voidLinklast (e e) {Finalnode<e> L =Last ; FinalNode<e> NewNode =NewNode<> (L, E,NULL);//Each additional node requires the newLast =NewNode; if(L = =NULL) First=NewNode; ElseL.next=NewNode; Size++; Modcount++; }

2. Add elements anywhere in the list

ArrayList: Based on an array implementation, an array requires a contiguous set of memory spaces, and if an element is inserted anywhere, the elements after that position need to be rearranged and inefficient.

      Public voidAddintindex, E Element) {Rangecheckforadd (index);//Check if index is out of boundsensurecapacityinternal (Size+ 1);//increments modcount!!System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index);//array replication is performed for each operation, and system.arraycopy can replicate the array itselfElementdata[index] =element; Size++; }        Private voidRangecheckforadd (intindex) {        if(Index > Size | | Index < 0)            Throw Newindexoutofboundsexception (outofboundsmsg (index)); }

      

LinkedList: The element at the specified position is first found, and then the element is inserted before the element. Insert elements at the end of the end, performance is high, insert in the middle position, low performance.

     //add an element at the specified position in the list      Public voidAddintindex, E Element) {Checkpositionindex (index);//Check if index is out of bounds        if(index = = size)//index is a list size, which is equivalent to adding elements at the end of the listlinklast (Element); ElseLinkbefore (element, node (index)); }    //returns the element of the specified index, which is fast at the end of the search, is slower in the middle position, and needs to traverse half the list of elements. Node<e> node (intindex) {        //assert Iselementindex (index);        if(Index < (size >> 1)) {//If index is in the first half of the list, the head of the node begins to traverse backwards .node<e> x =First ;  for(inti = 0; I < index; i++) x=X.next; returnx; } Else{//If index is in the second half of the list, the forward traversal starts from the tail node.node<e> x =Last ;  for(inti = size-1; i > Index; i--) x=X.prev; returnx; }    }    //add an element before specifying a node SUCC    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)//only one node of SUCCFirst =NewNode; ElsePred.next=NewNode; Size++; Modcount++; }

3. Delete any position element

    

ArrayList: The array is copied each time the delete occurs. The higher the location of the deletion, the greater the overhead, and the less expensive the deleted position.

     PublicE Remove (intindex) {Rangecheck (index);//Check if index is out of boundsModcount++; E OldValue=Elementdata (index); intnummoved = size-index-1; if(nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, Index, nummoved);//move the element that follows the delete position forward oneElementdata[--size] =NULL;//clear to let GC do it work last position set to null        returnOldValue; }

LinkedList: First the element to delete is found by looping, and then the element is deleted. Delete the elements of the end, the efficiency is high, delete the middle element, inefficient.

     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) {//x is the first elementFirst =Next; } Else{Prev.next=Next; X.prev=NULL; }        if(Next = =NULL) {//x is the last elementLast =prev; } Else{Next.prev=prev; X.next=NULL; } X.item=NULL; Size--; Modcount++; returnelement; }

4. Traversing the list

      

Three traversal modes: foreach, iterator, for traversal random access.

The internal implementation of foreach is also traversed using iterators, but because of the redundant assignment of foreach, it is slightly slower than the direct use of iterators and has little effect. For-traversal random access has a good performance on ArrayList and is disastrous for LinkedList.

Concurrent List

Vector and copyonwritearraylist are thread-safe implementations;

ArrayList is not thread-safe and can be packaged by collections.synchronizedlist (list).

Copyonwritearraylist, read operation does not need to lock,

  

1. Read operation

Copyonwritearraylist: Read Operation no lock operation

     Public E get (int  index) {        return  get (GetArray (), index);    }     Final object[] GetArray () {        return  array;    }         Private int index) {        return  (E) a[index];    }

Vector: Read operations need to add object lock, high concurrency situation, lock competition affect performance.

     Public synchronized E get (int  index) {        if (index >= elementcount)            throwNew  arrayindexoutofboundsexception (index);         return Elementdata (index);    }

2. Write operation

Copyonwritearraylist: A lock is required and each write operation requires an array copy for poor performance.

     Public BooleanAdd (e e) {FinalReentrantlock lock = This. Lock;        Lock.lock (); Try{object[] elements=GetArray (); intLen =elements.length; Object[] Newelements= arrays.copyof (elements, Len + 1);//generating an array copy by copyingNewelements[len] = e;//Modify a copySetArray (newelements);//writing a copy will            return true; } finally{lock.unlock (); }    }

Vector: and read the same need to add object lock, relative copyonwritearraylist do not need to copy, write performance than copyonwritearraylist higher.

     Public synchronized BooleanAdd (e e) {Modcount++; Ensurecapacityhelper (Elementcount+ 1);//confirm that expansion is requiredelementdata[elementcount++] =e; return true; }    Private voidEnsurecapacityhelper (intmincapacity) {        //overflow-conscious Code        if(Mincapacity-elementdata.length > 0) grow (mincapacity); }

Summary: In high concurrency applications where read and write less, it is appropriate to use copyonwritearraylist, and vectors are more suitable for high concurrency applications where read and write less.

Java data structure-------List

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.