Java Learning Notes-the implementation of class ArrayList and LinkedList

Source: Internet
Author: User

In the list under the collection collection two implementations are used very frequently, one is ArrayList, the other is LinkedList, in the study will certainly have this question: when is suitable to use ArrayList, when to use LinkedList? At this point, we need to understand the bottom-level implementation of ArrayList and LinkedList, below, in order to better understand how they are specifically implemented, we write their own ArrayList and LinkedList.

ArrayList the bottom layer is based on the implementation of the array, the array in memory is stored in a continuous storage unit, in the time of the data lookup is relatively fast, suitable for infrequently inserting data and need to find data frequently, we will implement it (to facilitate understanding, do not use generics, using object to store data ):

import java.util.arrays;/** *  Sequential storage structure: Implementation of class ArrayList  *  @author  liuzb *  August 8, 2017   PM 2:58:59 */public class sequencestroelinearlist{/** *  The number of elements that are actually stored in the storage container  */private int size = 0;/** *  the underlying container used to store the data  */private  Object[] container;/** *  in the sequential storage structure, used to initialize the  */private static final object [] empty_container = {};/** *  constructor for initializing containers that store data  */public  Sequencestroelinearlist () {This.container = empty_container;} The/** *  constructor, which initializes the container  */public sequencestroelinearlist (int mincapactiy)  {if for storing data ( mincapactiy > 0)  {container = new object[mincapactiy];} Else if (mincapactiy == 0)  {container = empty_container;} Else {throw new arrayindexoutofboundsexception ();}} /** *  add an element to a container  *  @param  index  add element position &NBsp;*  @param  element  add element  */public void insert (int index ,object  Element)  {//to insert data into an array: 1, the length of the array is not enough   2, the insertion position is not valid//if the insertion position is illegal, throw an index out of bounds exception if (index >  container.length | |  index <0)  {throw new arrayindexoutofboundsexception ();} else {//insertion Position Valid//If the data is inserted at the end if (index == container.length)  {container =  Arrays.copyof (container, ++size); container[index] = element;} else {//If you do not insert data at the end, first use the temporary variable to store the contents of the container object[] temp = container;//1, container point to a new container container  = new object[size+1];//copies the subscript of the original array from 0 to index into the expanded container system.arraycopy (temp, 0,  CONTAINER,&NBSP;0,&NBSP;INDEX);//2. Shift the data of index and its future position back to for (int i = size ; i  > index ; i--)  {container[i] = temp[i-1];} 3, insert the data CONTAINER[INDEX]&NBSP;=&NBSP;ELEMENT;//4, the number of elements plus a ++size;}}} /** *   adding data to a container  * @param  obj  objects to be added  */public void add (object obj)  {insert (size,obj);} The number of elements actually stored in the/** *  container  *  @return  */public int size ()  {return size;} /** *  gets the object at the specified index  *  @param  index  index at the specified location  *  @return   The object at the specified location  * /public object get (Int index)  {if (index <0 | |  index > size)  {throw new arrayindexoutofboundsexception ();} Return container[index];} /** *  gets the index of the specified object  *  @param  obj  object to get indexed  *  @return   Index   */ Public int indexof (object obj)  {int index = -1;for (int i = 0 ;  i<size ; i++)  {if (container[i].equals (obj))  {index = i;}} Return index;} Does the/** *  container contain an element  *  @param  obj *  @return  false  does not contain     true  includes &NBSP;*/PUBLIC&NBSp;boolean contains (object obj)  {return indexof (obj)  == -1 ? false  :true;} /** *  removes the elements of the specified index from the container  *  @param  index  Index of the element to be removed  *  @return   Remove  */ Public boolean remove (integer index)  {boolean flag = true;//  illegal index, Throw exception if  (index < 0 | |  index > size)  {flag = false;throw new  ArrayIndexOutOfBoundsException ("The removal of the specified index element failed, the index value is illegal");}  else {//  Index Legal for  (int i = index; i < size-1; i++)  {//the element index to size is shifted forward container[i] = container[i + 1];}   assigns the value of the end element to the number of  nullcontainer[size-1] = null;//  elements minus one-- size;} Return flag;} /** *  removes the specified element  *  @param  obj  elements to be removed   *  @return   true &NBSP: Remove success       false: Remove failed &NBSP;*/PUBLIC&NBSP;BOOLEAN&NBsp;remove (object obj) {if (contains (obj))  {remove (indexOf (obj)); return true;} Return false;}}

In the implementation, the arrays helper class under the Util package is used, and system.arraycpy () can also be used here.

After you have written the class, Test the class:

650) this.width=650; "Src=" https://s2.51cto.com/wyfs02/M00/9E/11/wKioL1mKy1ugjAkzAAIN-C4xw64618.jpg-wh_500x0-wm_ 3-wmp_4-s_4245678436.jpg "title=" 2017-08-09_164611.jpg "alt=" Wkiol1mky1ugjakzaain-c4xw64618.jpg-wh_50 "/>

From the implementation of the results, we basically realize the function of ArrayList, here the important two methods are inserting data and removing data, of course, the program also has a bug, is the Remove method.

LinkedList is based on the linked list, the data is inserted and deleted faster, suitable for frequent insertion and deletion operations, 650) this.width=650; "Src=" Https://s2.51cto.com/wyfs02/M01/9E /12/wkiol1mk0rzbld1paabi31t26be135.jpg-wh_500x0-wm_3-wmp_4-s_1513523474.jpg "title=" 2017-08-09_171707.jpg "alt=" Wkiol1mk0rzbld1paabi31t26be135.jpg-wh_50 "/> Here we implement a single linked list:

/** *  Custom Chained Storage list &nbsp: Single link list  *  @author  liuzb * 2017 August 9   Morning 11:24:07  */public class mysinglelinkedlist {/** *  first node in single-linked list  */private Node  header;/** *  the number of actual stored elements in the tail node  */private Node tail;/** *  single-linked list in a single-linked list  */ private int size;/** *  Inner class for encapsulating the data required by the node and the address of the next node  *  @author  liuzb *  2017 August 9   Morning 11:24:43 */private class node{/** *  data stored in the current list  */private  Object data;/** *  address of the next node stored by the current node  */private Node next;/** *  Parameterless constructor for node initialization  */public node ()  {}/** *  parametric constructor for node initialization  *  @param  date   node stored values  *  @param  next  The address of the next node that is saved in the node  */public node (object data,node  next)  {this.data = data;this.next = next;} /** *  gets the stored value of the current node  *  @return   node value  */ publiC object getdata ()  {return data;}} /** *  single-Strand header insertion  *  @param  item  data needs to be stored  */    public  Void addheader (Object item)  {    //Define a node     Node  node = null;    //if the original list is empty table     if (size == 0)  {     //constructs a new node, the next node of the node points to Null    node = new node (item, NULL);     //head and tail nodes point to new nodes     header = node;     tail = header;    }else {    //if the original linked list is not an empty table, Define a new node, and the next node of the new node points to the original head node     node = new node (item,header);     //new node becomes head node     header = node;    }   Number of   //elements plus one     size ++;    }    /**     *  single-linked list for insertion method      * @ param item  elements that require access      */     public void  addlast (Object item)  {    //Create a new node     node node  = new node (item,null);    //  if the original linked list is empty table     if ( size == 0)  {    //the head and tail nodes of the single-linked list point to the new node     tail =  header = node;    }else {    //the next node of the original tail node points to the new node     tail.next = node;    //new node becomes tail node      tail = node;    }    //the number of elements in a linked list plus a     size  ++;    }        /**      *  adding elements to a single-linked list &NBsp;    *  @param  item  elements to add      *  @return       */    public void add (Object item) The  {    //method inserts an element     addlast (item) By default by using the tail insertion method;     }        /**     *  remove elements from a specified position       *  @param  index  Index of elements to be removed      *  @return   True: Remove success    false: Remove Failure      */    public  Boolean remove (Int index)  {    boolean flag = false;     //If the index is illegal, throw an exception if  (index < 0 | |  index >= size)  {throw new indexoutofboundsexception ("Index of the removed element out of bounds");}  else {//If you remove the head node if  (index == 0)  {//The next node of the original head junction becomesThe head node Header = header.next;} Else if (index == size-1)  {//If the tail node is deleted, first obtain the previous node of the original tail node node node =  Getnodebyindex (index-1);///The previous node of the original tail node stores the next node address information to nullnode.next = null;//the previous node of the original tail node becomes the tail node tail  = node;} else {//deleted is neither the head node nor the tail nodes, the data that needs to be deleted is temporarily stored Node removenode = getnodebyindex (index);// Gets the previous node that needs to delete data Node node = getnodebyindex (index - 1);// Point the next node of the previous node to the next node of the node that needs to be deleted node.next = removenode.next;} Reduce the number of elements by one size -- ;flag = true;} return flag;    }        /**      *  get the node for the specified index      *  @param  index  The index value of the node you want to get      *  @return   Node Objects      */     Public node getnodebyindex (Int index)  {    node current =  header; &nBsp;  for (int i = 0;i < size && current !=  null;i++)  {    if (index == i)  {    return  current;    }    current = current.next;     }    return null;    }         /**     *  get the number of elements in a single-linked list      *  @return   Number of elements      */public int size ()  {return size;} /** *  Gets the node value for the specified index  *  @param  index  Index of the node to be obtained  *  @return   node value  */ Public object get (int index)  {//index is illegal, throws an exception if (index < 0 | |  index >= size)  {throw new arrayindexoutofboundsexception ("Cannot get the value of this Node");} Return getnodebyindex (Index). GetData ();} /** *  Insert data into the list at the specified location  *  @param  index  pending position  *  @param  item  data to be inserted  * @ return true  Insert succeeded     false  Insert failed  */public boolean insert (int  index,object item)  {boolean flag = true;if (index < 0 | |  index >size)  {flag = false;throw new arrayindexoutofboundsexception ();} If the head node is inserted before the IF (index == 0)  {header = new node (Item,header);} Else if (index == size)  {//insert into tail node//define a new node Node node = new node (item, NULL);//The next node of the tail node points to the new node tail.next = node;//the new node becomes the tail node Tail = node;} else {//a Node Node indexnode = getnodebyindex (index) that inserts a node between the first node and the tail node, and/or a new node is defined. The next node of the new node points to the node Node newnode = new node (Item,indexnode) at the original insertion position;//Gets the previous node of the insertion position Node node  = getnodebyindex (index-1);///The next node of the previous node of the insertion position points to the new node node.next = NewNode;} The number of elements plus a size ++ ;return flag;}     }

After writing the code, test the code:

650) this.width=650; "Src=" https://s2.51cto.com/wyfs02/M00/9E/13/wKiom1mK0hCBkqa2AAItEh1xheo045.jpg-wh_500x0-wm_ 3-wmp_4-s_2305761673.jpg "title=" 2017-08-09_171408.jpg "alt=" Wkiom1mk0hcbkqa2aaiteh1xheo045.jpg-wh_50 "/>

Above is a personal humble opinion, if there are errors, please point out, thank you!

This article is from the "Liu Zi blog" blog, please be sure to keep this source http://zibing.blog.51cto.com/8177516/1954864

Java Learning Notes-the implementation of class ArrayList 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.