Collection and Map (ii)--list system in Java

Source: Internet
Author: User

  

As we have seen in collection and map (a) in Java, we often use ArrayList, linkedlist, vectors, and stacks. There is no longer a way to describe how they are used, it is mainly about their underlying structure and the timing of their use.

1, ArrayList

We all know that ArrayList is one of the list collections that we often use. We often use the new ArrayList () method to create a ArrayList collection, and then call its Add (e) method to store the elements in the collection. So do you know what the bottom layer is doing when we use the New keyword to create a ArrayList collection? In fact, when we created the collection using New ArrayList (), the underlying created an array of type object, with an initialization length of 0, and when we first called the Add (e) method, the array length initialized me to 10. We all know that the ArrayList is not limited in length within a certain length. Since the initial ArrayList used to hold elements in the array length is 10, then when we add the 11th element, the array angle is crossed. This involves the expansion mechanism of ArrayList. Let's take a look at how ArrayList is expanding.

private void Grow (int mincapacity) {        //overflow-conscious code        int oldcapacity = elementdata.length;        int newcapacity = oldcapacity + (oldcapacity >> 1);        if (newcapacity-mincapacity < 0)            newcapacity = mincapacity;        if (newcapacity-max_array_size > 0)            newcapacity = hugecapacity (mincapacity);        Mincapacity is usually close to size, so this is a win:        Elementdata = arrays.copyof (Elementdata, newcapacity);    }

From the above code we find that ArrayList is in the time of expansion. The underlying array length increases the original 1/2. The data in the original array is copied to the new array by the Arrays.copyof method, and the original array points to the new array.

In summary: We know that the ArrayList underlying data structure is actually an array of type object. When we frequently want to add elements to the ArrayList, ArrayList expansion will affect a certain degree of efficiency.

2, LinkedList

LinkedList is also one of the list collections that we often use. LinkedList is used in much the same way as ArrayList. But LinkedList has some of its own unique methods (which derive from the different linkedlist and ArrayList underlying data structures)--addfirst (e E), AddLast (e e), let's take a look at the linkedlist underlying data structure.

Construction Method:

Public LinkedList () {
}

When we create the LinkedList collection through New LinkedList (), it's actually a simple Java class, but when we use the Add (E) method to add elements to the collection, it's different from ArrayList.

    Public voidAddFirst (e e) {Linkfirst (e); } Public voidAddLast (e e) {linklast (e); } PublicBoolean Add (E e) {linklast (e); return true; }voidLinklast (e e) {final Node<E> L =Last ; Final Node<E> NewNode =NewNode<> (L, E,NULL); Last=NewNode; if(L = =NULL) First=NewNode; ElseL.next=NewNode; Size++; Modcount++;}Private voidLinkfirst (e e) {final Node<E> f =First ; Final Node<E> NewNode =NewNode<> (NULL, E, f); First=NewNode; if(f = =NULL) Last=NewNode; ElseF.prev=NewNode; Size++; Modcount++;} Private Static classNode<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; }    }

We Linkfirst or Linklast methods from the source code, either AddFirst, AddLast, or Add method calls, and Linklast connects them by pointing the node nodes together. From this we can see that LinkedList is a custom data structure---linked list, in the Add (e) method does not involve the expansion of the problem.

3, ArrayList and LinkedList comparison
    1. ArrayList is the realization of the data structure based on dynamic array, LinkedList data structure based on the linked list.
    2. For random access get and set,arraylist better than LinkedList, because linkedlist to move the pointer.
    3. Add and remove,linedlist are the dominant for new and deleted operations, because ArrayList to move data and increase the data will involve the expansion (here is only theoretical analysis, in fact, not necessarily, ArrayList at the end of the insertion and deletion of data, Faster than LinkedList).
    4. Randomly finding the operation of a specified node get,arraylist faster than LinkedList.
4. Vector

The underlying vector is also implemented using an array structure. As a whole, it is similar to ArrayList. But there are differences:

    1. Vector methods are synchronous (Synchronized), is thread-safe (Thread-safe), and ArrayList method is not, because the thread synchronization must affect performance, therefore, ArrayList performance than vector good.
    2. When an element in a vector or ArrayList exceeds its initial size, the vector doubles its capacity, while the ArrayList only increases the size by 50%, so that the ArrayList is useful for saving memory space.
Vector Expansion Method:
private void Grow (int mincapacity) { //overflow-conscious code int oldcapacity = elementdata.length; int newcapacity = oldcapacity + ((capacityincrement > 0)? capacityincrement:oldcapacity); if (newcapacity-mincapacity < 0) newcapacity = mincapacity; if (newcapacity-max_array_size > 0) newcapacity = hugecapacity (mincapacity); Elementdata = arrays.copyof (Elementdata, newcapacity); }
5. Stack (Stack)

It is a subclass of a vector. The stack (stack) feature is advanced and post-out.

The Stack class represents a last-in, first-out (LIFO) object heap. It extends the class vector by five operations, allowing the vector to be treated as a stack.  It provides the usual push and pop operations, and the Peek method that takes the stack vertex, the empty method that tests if the stack is null, the search method that finds the item in the stack, and determines the distance to the top of the stack.  When the stack is first created, it does not contain items. Direct stack () creates an empty stack method summary:
Method Summary
 boolean empty()
Tests whether the stack is empty.
 E peek()
View the object at the top of the stack, but not remove it from the stack.
 E pop()
Removes the object at the top of the stack and returns the object as the value of this function.
 E push(E item)
Press the item onto the top of the stack.
 int search(Object o)
Returns the position of the object in the stack, with a base of 1.
Let's look at the source of stack:
Publicclass stack<e> extends Vector<e> {/** * creates an empty Stack. */Public Stack () {}/** * pushes a item onto the top of this stack. This has exactly * the same effect as: * <blockquote><pre> * addelement (item) </pre></bloc     kquote> * * @param item The item to is pushed onto this stack.     * @return the <code>item</code> argument.        * @see Java.util.vector#addelement */public E push (e Item) {addelement (item);    return item;     }/** * Removes the object at the top of this stack and returns that * object as the value of this function. * * @return The object at the top of this stack (the last item * of the <tt>Vector</tt> o     bject).     * @throws emptystackexception If this stack is empty.        */public synchronized e pop () {e obj;        int len = size ();        obj = Peek (); RemoveelemEntat (len-1);    return obj;     }/** * Looks at the "the object" at the top of the "this" stack without removing it * from the stack. * * @return The object at the top of this stack (the last item * of the <tt>Vector</tt> Obje     CT).     * @throws emptystackexception If this stack is empty.        */Public synchronized E peek () {int len = size ();        if (len = = 0) throw new emptystackexception ();    Return ElementAt (len-1);     }/** * Tests If this stack is empty. * * @return <code>true</code> If this stack contains * no items;     <code>false</code> otherwise.    */public Boolean empty () {return size () = = 0;     }/** * Returns the 1-based position where an object was on this stack. * If The object <tt>o</tt> occurs as an item in this stack, this * method returns the distance from the P The stack of the * OCCurrence nearest the top of the stack; The topmost item on the * stack are considered to being at distance <tt>1</tt>.     The <tt>equals</tt> * method is used to compare <tt>o</tt> to the * all items in this stack.     * * @param o the desired object. * @return The 1-based position from the top of the stack where * the object is located;     The return value <code>-1</code> * Indicates, the object is not on the stack.        */Public synchronized int search (Object o) {int i = lastIndexOf (o);        if (I >= 0) {return size ()-I;    } return-1; }/** use Serialversionuid from JDK 1.0.2 for interoperability */private static final long Serialversionuid = 12244 63164541339165L;}
    1. Note the object at the top of the "This" stack (the last item of the vector object, which can be found in the array (vector) at the top of the stack by using the Peek () method
    2. The pop, peek, and search methods themselves are synchronized
    3. The push method invokes the AddElement method of the parent class
    4. The empty method invokes the size method of the parent class
    5. Vector class for thread-safe classes

In summary, the stack class is a thread-safe class

The stack does not require the uniqueness of the data to be saved, and when there are multiple identical item in the stack, the search method is called, returning only the item equal from the top of the stack and the distance from the top of the stack.

Collection and Map (ii)--list system in Java

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.