Java Improvement Chapter (32)-----List Summary

Source: Internet
Author: User

The previous LZ has fully introduced a lot of knowledge about the list interface, such as ArrayList, LinkedList, Vector, Stack, which can have a deeper understanding of the list interface through these knowledge points. Only by summarizing the knowledge is your knowledge. So the following LZ on the list interface to do a summary. Recommended reading:

Java Improvement (21)-----ArrayList

Java Improvement (22)-----LinkedList

Java Improvement Chapter (29)-----Vector

Java Improvement Chapter (31)-----Stack

I. Overview of the list interface

The list interface becomes an ordered sequence of collection. The interface provides precise control over the insertion position of each element in the list, and at the same time the user is able to access elements based on the integer index of the element (in the list) and search for the elements in the list. is the frame diagram of the list interface:


through the above frame diagram, the structure of the list can be clear to the heart, its various classes, interfaces such as the following:

Collection: The root interface in the Collection hierarchy. It represents a set of objects, also known as collection elements. For collection, it does not provide any direct implementation, and all implementations are owned by its subclasses.

Abstractcollection: Provides a backbone implementation of the Collection interface to minimize the work required to implement this interface. For us to implement an immutable collection, we just need to extend this class and provide implementations of the iterator and size methods. However, to implement the collection, you must override the Add method of this class (otherwise, throw unsupportedoperationexception), and the iterator returned by the iterator method must implement its Remove method separately.

Terator: iterator.

Listiterator: Series table iterator, consent program the ape traverses the list in either direction, changes the list during iteration, and gets the current position of the iterator in the list.

List: An interface that inherits from the collection. It represents an orderly queue.

abstractlist: The backbone of the List interface is implemented to minimize the work required to implement this interface that is supported by the random Access data store (such as arrays).

Queue: Queues. Provides the primary insert, FETCH, and check operations for the queue.

Deque: a linear collection that supports inserting and removing elements at both ends. Most Deque implementations have no fixed limit on the number of elements they can include, but this interface supports both a capacity-constrained double-ended queue and a double-ended queue without a fixed limit size.

Abstractsequentiallist: Provides a backbone implementation of the List interface to minimize the effort required to implement this interface supported by a "continuous access" data store, such as a linked list. In a sense, this class implements the "Random access" method on a list iterator on a list.

LinkedList: The list interface is implemented as a link listing. It implements all the optional list operations.

ArrayList: The implementation of a variable array of size for the List interface. It implements all optional list operations and agrees to all elements, including null. In addition to implementing the list interface, this class provides methods to manipulate the size of the array used internally to store the list.

Vector: Implements an array of objects that can grow. Like an array, it includes components that can be interviewed using an integer index.

Stack: Last-in, first-out (LIFO) object stacks. It extends the class vector by five operations, agreeing to treat the vector as a stack.

enumeration: enumeration that implements the object of the interface, which generates a series of elements, one at a time. Successive calls to the Nextelement method will return a series of contiguous elements.


second, the use of the scene

The fundamental purpose of learning knowledge is to use it. every knowledge point has its scope of use. The same is true for collections, where the family of collections in Java is large and each member has the most appropriate usage scenario. In the first contact list, LZ said that the assumption involves "stack", "queue", "linked list" and other operations, please consider using list. As for the list, the following are the points:

1, for the need for high-speed insertion, deletion of elements, you need to use LinkedList.

2, for the need for high-speed access to elements, you need to use ArrayList.

3, for "single-threaded Environment" or "multi-threaded environment, but list is only one thread operation", you need to consider the use of non-synchronous classes, assume that "multithreaded environment, the list may be multiple threads at the same time", consider using synchronized classes (such as vectors).

2.1ArrayList, LinkedList performance Analysis

The most common things we use in List are LinkedList and ArrayList, and at the same time we understand the usage scenarios and differences between them.

public class Listtest {private static final int COUNT = 100000;    private static ArrayList ArrayList = new arraylist<> ();    private static LinkedList LinkedList = new linkedlist<> ();        private static vector vector = new vector<> ();        public static void Inserttolist (List list) {Long startTime = System.currenttimemillis ();        for (int i = 0; i < COUNT; i++) {list.add (0,i);        } Long EndTime = System.currenttimemillis ();    System.out.println ("Insert" + COUNT + "element" + getName (list) + "spend" + (Endtime-starttime) + "millisecond");                public static void Deletefromlist (List list) {Long startTime = System.currenttimemillis ();        for (int i = 0; i < COUNT; i++) {list.remove (0);        } Long EndTime = System.currenttimemillis ();    System.out.println ("delete" + COUNT + "element" + getName (list) + "spend" + (Endtime-starttime) + "millisecond"); } public static void ReaDlist (List list) {Long startTime = System.currenttimemillis ();        for (int i = 0; i < COUNT; i++) {list.get (i);        } Long EndTime = System.currenttimemillis ();    System.out.println ("read" + COUNT + "element" + getName (list) + "spend" + (Endtime-starttime) + "millisecond");        } private static string GetName (List list) {string name = "";        if (list instanceof ArrayList) {name = "ArrayList";        } else if (list instanceof linkedlist) {name = "LinkedList";        } else if (list instanceof vector) {name = "vector";    } return name;        } public static void Main (string[] args) {inserttolist (arrayList);        Inserttolist (LinkedList);                Inserttolist (vector);                System.out.println ("--------------------------------------");        ReadList (arrayList);        ReadList (LinkedList);                ReadList (vector); System.out.println("--------------------------------------");        Deletefromlist (arrayList);        Deletefromlist (LinkedList);    Deletefromlist (vector); }}

Execution Result:

Inserting a 100000 element ArrayList takes 3900 milliseconds to insert a 100000 element LinkedList takes 15 milliseconds to insert a 100000 element vector cost 3933 Milliseconds--------------------------------------reads 100000 elements ArrayList takes 0 milliseconds to read 100000 elements LinkedList takes 8877 milliseconds to read 100000 elements vector cost 16 Ms--------------------------------------Delete 100000 elements ArrayList takes 4618 milliseconds to delete 100000 elements LinkedList cost 16 Milliseconds to delete 100000 elements vector takes 4759 milliseconds

from the above results we can clearly see the efficiency of ArrayList, LinkedList, vector addition, deletion, traversal. The following I insert method Add (int index, E element), delete, get methods you are interested to be able to study.

First we look at the source code between the three:

ArrayList

public void Add (int index, E element) {        Rangecheckforadd (index);   Check if index is legal        ensurecapacityinternal (size + 1);  Expansion Operation        System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index);    Array copy        Elementdata[index] = element;   Insert        size++;    }

Rangecheckforadd, ensurecapacityinternal Two methods have no effect, the real impact is the System.arraycopy method, the method is a JNI function, is implemented in the JVM. Declarations such as the following:

public static native void Arraycopy (object src, int srcpos, object dest, int destpos, int length);

LZ can not see the source code at the moment, the detailed implementation is not very clear, but System.arraycopy source code analysis of it is relatively clear analysis. But actually we just need to know that this method will move all the elements behind index, which means that the ArrayList add (int index, E Element) method will cause all elements to change after the index position, which is really holding the whole body.

LinkedList

public void Add (int index, E element) {        Checkpositionindex (index);        if (index = = size)     //Insert position at the end of            linklast (element);        else                               Linkbefore (element, node (index));    }

The method is relatively simple, the insertion position at the end of the call Linklast method, or call the Linkbefore method, in fact Linklast, Linkbefore are very easy to implement, that is, the index position to insert elements, As for index details, there is a node method to solve, at the same time node to the index position to retrieve another acceleration effect, such as the following:

node<e> node (int index) {        if (Index < (size >> 1)) {    //assuming that index is less than SIZE/2 start from scratch to find            node<e> x = First;            for (int i = 0; i < index; i++)                x = X.next;            return x;        } else {   //assume that index is greater than SIZE/2 to find            node<e> x = last from the tail;            for (int i = size-1; i > Index; i--)                x = X.prev;            return x;        }    }

so the LinkedList insert action is faster than the ArrayList action is in two aspects. 1:linkedlist does not need to perform element copy action, no reaching. 2: Find the insertion position there is an acceleration action: If the index < two-way list length of 1/2, then the former search backward; Otherwise, look forward from behind.

Vector

vector Implementation mechanism and ArrayList, the same is done using dynamic arrays, so they are almost the same efficiency between the two, add the same source code, such as the following:

public void Add (int index, E element) {        Insertelementat (element, index);    }        Public synchronized void Insertelementat (E obj, int index) {        modcount++;        if (Index > Elementcount) {            throw new ArrayIndexOutOfBoundsException (index                                                     + ">" + elementcount);        }        Ensurecapacityhelper (Elementcount + 1);        System.arraycopy (Elementdata, index, Elementdata, index + 1, elementcount-index);        Elementdata[index] = obj;        elementcount++;    }

The above is an explanation of the add (int index,e Element) method between ArrayList, LinkedList, and vector, explaining that the LinkedList insert action is more than ArrayList, The efficiency of the insertion action of vectors is so much higher! As for the delete, get two methods LZ is not much explanation.

at the same time the LZ wrote the example above and found a very interesting phenomenon, that linkedlist at some point when the Add method is more than the ArrayList method will be slower! As to what is the situation? Why slow LZ Next blog explanation, of course, do not know this situation have you ever met??

2.2. The difference between vector and ArrayList


Four, many other

Java Improvement (21)-----ArrayList

Java Improvement (22)-----LinkedList

Java Improvement Chapter (29)-----Vector

Java Improvement Chapter (31)-----Stack

-----Original from: http://cmsblogs.com/?p=1201 , please respect the author's hard work results, reproduced the source of the explanation.

-----personal website: http://cmsblogs.com

Java Improvement Chapter (32)-----List Summary

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.