Java Collection (2)--deep understanding of ArrayList, vectors, and LinkedList

Source: Internet
Author: User
Tags array length prev

Review

The Java collection is divided into two architectures, collection and maps. This blog mainly introduces the three commonly used implementation classes under the collection sub-interface list: ArrayList, vectors, and LinkedList.

See "Java Basics-Collections" For more information

First look at the diagram:

1, ArrayList

This is the most common implementation class for list, think about why he is most used?
Array, which in Java is "arrays". Guess ArrayList and arrays should be very closely related, in fact ArrayList can be regarded as a size can be changed array.

For a simple example, look at his use:

Arraylist<string> List1 = new Arraylist<> ();List1. Add("a");List1. Add("B");List1. Add("C");List1. Set(2,"D");iterator<string> iter = List1. Iterator();while (ITER. Hasnext()) {System. out. println(ITER. Next());}

After that, let's see how he designed it from the source.

1) constructor function

Tips:
The default ArrayList length is 10;
The elementdata used to hold the data itself is a object[];
ArrayList provides three types of constructors, which can be seen in the following code.

 Public  class ArrayList<e> extends abstractlist<e> C8>implements List<E;, randomaccess, cloneable, Java . io. Serializable {   //default capacity is ten    Private Static Final intDefault_capacity =Ten;Private Static FinalObject[] Empty_elementdata = {};//Call a parameterless constructor, give an empty data    Private Static FinalObject[] Defaultcapacity_empty_elementdata = {};//Save the data for the elementTransient object[] elementdata;///1, parameterless constructor, default empty array      PublicArrayList () { This. Elementdata = Defaultcapacity_empty_elementdata; }///2, given the initial capacity of the constructor      PublicArrayList (intinitialcapacity) {//greater than 0 o'clock, creates an object data with a length of incoming capacity value        if(Initialcapacity >0) { This. Elementdata =NewObject[initialcapacity]; }Else if(Initialcapacity = =0) {//equals 0 o'clock, gives an empty array             This. Elementdata = Empty_elementdata; }Else{//Other thrown capacity illegal exception            Throw NewIllegalArgumentException ("Illegal capacity:"+ initialcapacity); }    }//3, constructor for a given collection object      PublicArrayList (collection<? extends e> c) {//Put in an arrayElementdata = C.toarray ();//Array length is not equal to 0 o'clock and will be copied        if((size = elementdata.length)! =0) {//C.toarray might (incorrectly) not return object[] (see 6260652)            if(Elementdata.getclass ()! = object[].class) Elementdata = arrays.copyof (elementdata, size, object[].class); }Else{Otherwise, an empty array is returned This. Elementdata = Empty_elementdata; }    }}

2) Dynamic expansion
When adding an element, there is an extension problem, with the core approach being grow ().

Tips:

">>" right-shift operator:
Easy to understand in binary, this is not the point, roughly equivalent to One-second of the value. Therefore, some books will say that ArrayList expansion once will increase the original half, is seen from here.

 private   void  grow  (int  mincapacity) {//Gets the original capacity, that is, the length of the original array  int  oldcapacity = elementdata.length;        //new capacity  int  newcapacity = oldcapacity + (oldcapacity >> 1
     ); if         (Newcapacity-mincapacity < 0 ) newcapacity = mincapacity; if         (Newcapacity-max_array_size > 0 ) newcapacity = hugecapacity (mincapacity);    //copy array  elementdata = arrays.copyof (Elementdata, newcapacity); }
2. Vector

Vector and ArrayList are almost identical, directly to see the source code to know, an instant kind of plagiarism bright ...
But in fact not, vector is more than ArrayList appeared early, and precisely because of this, many methods are relatively old, not recommended for male.

Here a little bit of code, and ArrayList almost the same, do not occupy space, there is an interest to go to java.util.Vector inside to turn over.

 Public  class Vector<e> extends abstractlist<e>  Implements List<E;, randomaccess, cloneable, Java . io. Serializable {   protectedObject[] Elementdata;protected intElementcount; PublicVector () { This(Ten); } PublicVector (intInitialcapacity,intCapacityincrement) {Super();if(Initialcapacity <0)Throw NewIllegalArgumentException ("Illegal capacity:"+ initialcapacity); This. Elementdata =NewObject[initialcapacity]; This. capacityincrement = capacityincrement; }

Of course, Vector has some of its own characteristics, take a few ways to see. Almost all of his methods use the Synchronized keyword, which is much more expensive and slower to run.

  Public synchronized void Copyinto(object[] Anarray) {System.arraycopy (Elementdata,0, Anarray,0, Elementcount); } Public synchronized void setSize(intnewSize) {} Public synchronized int capacity() {returnElementdata.length; }//Number of arrays       Public synchronized int size() {returnElementcount; }//Get elements     PublicEnumeration<e>Elements() {return NewEnumeration<e> () {intCount =0; Public Boolean hasmoreelements() {returnCount < Elementcount; } PublicEnextelement() {synchronized(Vector. This) {if(Count < Elementcount) {returnElementdata (count++); }                }Throw NewNosuchelementexception ("Vector Enumeration");    }        }; }
3, LinkedList

is a doubly linked list, with Add and remove performance better than ArrayList, but get and set are particularly slow.

To fill in the evil:
Doubly linked list, one of the linked lists. There are two pointers in each data node, pointing to direct precursors and direct successors, respectively. Therefore, we can conveniently access his precursor nodes and subsequent nodes.


is a diagram of a doubly linked list, element is a component, the pre points to a direct precursor (the previous element), and next points directly to the successor (the latter element). And LinkedList is not just a doubly linked list, he is a two-way loop linked list. That is, the first pre pointer points to the last node, and the next pointer of the last node points to the first node, forming a loop instead of NULL in.

Here's a look at the code

 Public  class LinkedList<E> extends abstractsequentiallist<  E> implements List<e;, Deque<e;,  Cloneable, java. io. Serializable {    //Number of elementsTransientintSize =0;//equivalent to the pre pointerTransient node<e> first;//equivalent to next pointerTransient node<e> last;//node Inner class (doubly linked list structure)    Private Static  class Node<E> {E item;        Node<e> Next;        Node<e> prev; Node (node<e> prev, E element, node<e> next) { This. item = element; This. next = Next; This. prev = prev; }    }    ......}

Tips:

Deque, he is a dual-ended queue interface that supports inserting and removing elements at both ends.

Public interface Deque extends Queue {}

So how do you do it? Here is an example of adding elements in an intermediate position.

The code is implemented as follows

  //Add element at specified location  Public voidAddint Index, E Element) {//Check if index is validCheckpositionindex (Index);//index value equals the collection size, added directly at the end        if(Index= = size) linklast (element);ElseLinkbefore (Element, node (Index)); }//Returns the non-null node at indexNode<e> node (int Index) {//Assert Iselementindex (index);        //If the first half of the list        if(Index< (size >>1) {node<e> x = first; for(inti =0; I <Index; i++) x = X.next;returnX }Else{//second half segmentNode<e> x = Last; for(inti = size-1; i >Index; i--) x = X.prev;returnX }    }//middle Insert Element (Core Method!!!!) )     voidLinkbefore (e E, node<e> succ) {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++; }

For the performance of this piece, in the Big data volume repeated experiment to draw the conclusion is more persuasive, small series on the hand to paste their own test results, interested to see on it.

The test code is almost like this ...

arraylist<integer> ArrayList = new Arraylist<integer> ();linkedlist<integer> LinkedList = new Linkedlist<integer> ();//AddOperation int count =100000;System. out. println("Arraylist--add ()-------------------");Long StartTime = System. Nanotime();for (int i =0; i < count; i++) {ArrayList. Add(i);} Long EndTime = System. Nanotime();System. out. println(Endtime-starttime +"--------");System. out. println("Linkedlist--add ()-------------------");StartTime = System. Nanotime();for (int i =0; i < count; i++) {LinkedList. Add(i);} endTime = System. Nanotime();System. out. println(Endtime-starttime +"--------");

Looping 1W times

Looping 10W times

Looping 100W times

Wait a minute......
Wait a minute......
Wait a second ...
Go out and pick up a glass of water ...

The result is still like this, give a diagram directly, LinkedList not get Out (⊙﹏⊙) b

Well...... This is almost over.

Java Collection (2)--deep understanding of ArrayList, vectors, 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.