Java Collection of dry goods-inventory list source code analysis, dry goods inventory list

Source: Internet
Author: User

Java Collection of dry goods-inventory list source code analysis, dry goods inventory list
Preface

In the previous article, we analyzed ArrayList in detail. Today we will talk about 'arraylist. What is the difference between them? The biggest difference is that the underlying data structure is implemented differently. ArrayList is implemented by arrays (see the previous article), and LinedList is implemented by a linked list. As for some other differences, it can be said that most of them are different applications derived from different nature.

Linked List

Before analyzing the LinedList, let's give a brief introduction to the linked list. After all, the linked list is not used much like an array, so it is inevitable that many people are unfamiliar with it.

The linked list is a basic linear data structure, which is linear with arrays, but the physical storage of the array is linear and logical. The linked list is linear only in logic. Each storage unit in the linked list not only stores the current element, but also the address of the next storage unit. In this way, all the storage units can be connected through the address.

Each time you search, you can find the desired elements by using the first storage unit. To delete an object, you only need to disconnect the corresponding element. As follows:

2011-1-10_114030 2018-01-10_114053 2018-01-10_114109

Of course? A two-way linked list is not the most basic one-way linked list.

There is a basic storage unit in LinedList, which is an internal class of the shortlist. The Node element has two attributes to save the references of the previous node and the next node respectively.

// Static internal class private static class Node <E >{// store the attribute E item of the element; // The front and back nodes reference Node <E> next; Node <E> prev; node (Node <E> prev, E element, Node <E> next) {this. item = element; this. next = next; this. prev = prev ;}}

 

Definition
public class LinkedList<E>    extends AbstractSequentialList<E>    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

 

The definition is not very different from that of ArrayList, but it should be noted that the inclulist implements Deque (indirectly implements the Qeque Interface), and Deque is a two-way pair column, the LinedList provides a method to access elements from both ends of the column.

Initialization

When analyzing ArrayList, we know that the initialization length of ArrayList when using the non-argument constructor is 10, and all sets constructed without parameters will point to the same object array (static constant, in the method area), what is the initialization of the consumer list?

Open the construction method without Parameters

public LinkedList() {}

 

If there is nothing, you can only view the attributes.

// The initialization length is 0 transient int size = 0; // There are front and back nodes with transient Node <E> first; transient Node <E> last;

 

Graph Initialization

LinkedList<String> list = new LinkedList<String>();        String s = "sss";        list.add(s);

 

Method add (E)
public boolean add(E e) {  linkLast(e);  return true;}

 

From the method, we know that after the method is called, The linkLast method is not immediately added, but called. The new element is added at the end of the set.

Void linkLast (E e) {// assign a value to the last element (pass the reference) after assigning values to the properties modified by Node l final modifier, the final Node cannot be changed <E> l = last; // call the parameter constructor of the Node to create a new Node and save the added final Node <E> newNode = new Node <> (l, e, null ); // at this time, the new node is the last element that assigns the new node the value of last = newNode; // if l is null, it means that this is the first time an element is added. if l is null, the first value is assigned to the new node. This list has only one element to store the start element and the last element is the same element. if (l = null) first = newNode; else // if it is not the first addition, assign the new node to next l (the last element before addition. next = newNode; // Length + 1 size ++; // number of modifications + 1 modCount ++ ;}

 

From the code above, we can see that it does not depend on subscript when adding elements.

The processing is to save the information of the last Node (actually the last Node) through a last (Node object), and add elements each time by constantly changing the last element. (To fully understand the difference and essence between java value transfer and reference transfer, we need to understand ).

Add (int index, E element)
Add to the specified position public void add (int index, E element) {// check checkPositionIndex (index) for subscripts out of bounds ); // call linkLast if (index = size) linkLast (element) directly to the end; // call linkBefore else linkBefore (element, node (index) vice versa ));} // Insert the void linkBefore (E e, Node <E> succ) element before the specified element {// assert succ! = Null; suppose assertion succ is not null // define a Node element to save the prev reference of succ, that is, its previous Node information final Node <E> pred = succ. prev; // create a new Node element. e prev references the element to be inserted, that is, pred, that is, the previous element of succ before insertion. next is succ final Node. <E> newNode = new Node <> (pred, e, succ); // at this time, the previous node of succ is the newly inserted node. Therefore, modify the node to point to succ. prev = newNode; // if pred is null, it indicates this is the first element. if (pred = null) // The member attribute first points to the new node first = newNode; // otherwise, else // The next attribute of the element before the node points to the new node pred. next = newNode; // Length + 1 size ++; modCount ++ ;}

 

Node element insertion illustration

In the code above, we should note that when inserting an element in the subscripts list, we should also perform some verification, that is, the subscripts should be out-of-bounds verification. Let's take a look at the specific implementation below.

Private void checkPositionIndex (int index) {if (! IsPositionIndex (index) throw new IndexOutOfBoundsException (outOfBoundsMsg (index);} // If the input index is within the range, tureprivate boolean isPositionIndex (int index) is returned) {return index >=0 & index <= size ;}

 

Through the analysis of the two adding methods, we can clearly feel the efficiency of adding elements to the tranquility list, without resizing or copying arrays.

Get
Public E get (int index) {// check whether the subscript element exists is actually checking whether the subscript exceeded the checkkelementindex (index ); // if there is no cross-border, return the item of the corresponding subscript node, that is, the corresponding element return node (index ). item;} // subscript out-of-bounds check. if out-of-bounds check is performed, an exception is thrown. private void checkElementIndex (int index) {if (! IsElementIndex (index) throw new IndexOutOfBoundsException (outOfBoundsMsg (index);} private boolean isElementIndex (int index) {return index> = 0 & index <size ;} // This method is used to return the non-empty Node <E> node (int index) of the specified subobject) {// assume that the subscript does not actually cross the border. After all, the subscript cross-border check is executed before this. // assert isElementIndex (index ); // if the index is smaller than 1/2 of the size, search for (backward); otherwise, search for if (index <(size> 1 )) {// high left-Shift Efficiency worth learning Node <E> x = first; // traverse for (int I = 0; I <index; I ++) // The next of each node is referenced and traversed by another node. x will be assigned to the next element of the node constantly and traversed to the index, which is the element x of the corresponding node of the index. = x. next; return x;} else {Node <E> x = last; for (int I = size-1; I> index; I --) x = x. prev; return x ;}}

 

This Code fully demonstrates the superiority of the two-way linked list. It can be traversed from the back to the front, and the efficiency can be significantly improved by judging the index range. However, during traversal, we can also see that the low efficiency of getting elements by using the retrieve list get method, and the time complexity is O (n ).

Remove (int index)

To delete a node, you can set the reference before and after the node to null, and ensure that no other node points to the deleted node.

Public E remove (int index) {// check checkElementIndex (index ); // The returned value here is actually two methods are executed // node gets the specified non-empty node // unlink disconnects the specified node return unlink (node (index ));} E unlink (Node <E> x) {// assume that x is not null // assert x! = Null; // defines a variable element. Accepting the elements in the x node will return the final E element = x. item; // define the connected nodes to obtain the front and back nodes of x respectively. Reference final Node <E> next = x. next; final Node <E> prev = x. prev; // if null is referenced before a node, this is the first node if (prev = null) {// x indicates that the first node is about to be deleted. Therefore, the first node must be assigned a value of first = next ;} else {// if not x is not the first node, direct the next of prev (the previous node of x) to the next node of x (bypassing x) prev. next = next; // The first reference of x is assigned null x. prev = null;} // if the post-node reference is null, this indicates that this is the last node. if (next = null) {last = prev ;} else {next. prev = prev; x. next = null;} // assign null x to the element in node x. item = null; size --; modCount ++; return element ;}

 

Description

Summary of the differences between ArrayList and rule list
  • After all, the ArrayList needs to copy the array and resize it.
  • I cannot ensure that everything is correct, but I can ensure that every line of code in every sentence is under scrutiny and consideration. I hope that every article is backed by my own attitude towards pure technological life.

    Always believe that beautiful things will happen soon.

    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.