Java collection of ArrayList source code analysis

Source: Internet
Author: User
Tags addall

1. Introduction

List in the data structure is expressed as a linear table, its elements are stored in a linear manner, the collection allows to store duplicate objects, list interface main implementation classes have ArrayList and linkedlist. Java provides the implementation of these two structures, this article is to be familiar with the next ArrayList of the source code implementation. Examples of use are:

  

Package Com.test.collections;import Java.util.arraylist;public class Arraylisttest {/** * @param args */public static voi D main (string[] args) {//TODO auto-generated method stubarraylist<string> arrayList = new Arraylist<string> ( ), Arraylist.add ("A"), Arraylist.add ("B"), Arraylist.add ("C"), Arraylist.add ("D"), Arraylist.add ("E"); System.out.println (Arraylist.add ("F")); System.out.println (Arraylist.contains ("A")); System.out.println (Arraylist.indexof ("E")); System.out.println (Arraylist.contains ("A")); System.out.println (Arraylist.clone ()); System.out.println (Arraylist.lastindexof ("D")); System.out.println (Arraylist.remove (1)); System.out.println (Arraylist.remove ("A")); Arraylist.trimtosize (); Arraylist.add (1, "N"); Arraylist.clear ();}}

  

2. Inheritance structure

ArrayList inherited the Abstractlist<e>, and realized List<e>,randomaccess, cloneable, serializable these interfaces, In the interior of the ArrayList there is the privatization of the internal class ITR inheritance implemented Iterator<e> interface, Listitr inherited Arraylist<e>. Itr and implements the Listiterator<e> interface. You can use the related methods of iterators.

3. Source Code Analysis

  A: Related properties

Through the source code can be found that the ArrayList implementation class contains properties have private static final int default_capacity = 10;private static final object[] Empty_elementdata = new Object[0];p rivate transient object[] elementdata;p rivate int size; private static final int max_array_size = 2147483639;

default_capacity : Default initialized array size by default

empty_elementdata : Creating an empty initialization array

elementdata: instantaneous array records the element that holds the array list (the Transient keyword identifies the genus's performance and the object is serialized serially)

Size: Identifies how large the record list is

max_array_size : The maximum number of elements allowed in an array

B: Construction method

  

Public ArrayList (int paramint) {if (Paramint < 0) throw new IllegalArgumentException ("Illegal capacity:" + paramint); th Is.elementdata = new Object[paramint];} Public ArrayList () {this.elementdata = Empty_elementdata;} Public ArrayList (collection<? extends e> paramcollection)  {    This.elementdata = Paramcollection.toarray ();    This.size = this.elementData.length;    if (this.elementData.getClass () = = [Ljava.lang.Object.class]      return;    This.elementdata = arrays.copyof (This.elementdata, this.size, [Ljava.lang.Object.class);  }

Through the source code we can find that Aarraylist provides three types of constructors: the parameterless constructor ArrayList () is an empty ArrayList, and a constructor with an shaping parameter ArrayList (int) equals the initialization of a fixed capacity ArrayList; Provides a constructor that contains audit parameters ArrayList (Collection) is by copying the data in the collection into the new ArrayList and assigning it to elementdata;

C:trimetosize ()

public void TrimToSize () {This.modcount + = 1;if (this.size >= this.elementData.length) Return;this.elementdata = Arrays.copyof (This.elementdata, this.size);}

Through the source code can be found that the role of the entire method is to remove the empty unused null space. The function only removes the reserved element position, and then the element size is the smallest size that the ArrayList holds.

D:inexof (object) and LastIndexOf (object)

public int indexOf (Object paramobject) {int i;if (paramobject = = null) for (i = 0; i < this.size; ++i) if (THIS.ELEMENTDA Ta[i] = = null) return i;elsefor (i = 0; i < this.size; ++i) if (Paramobject.equals (This.elementdata[i])) return I;return- 1;} public int lastIndexOf (Object paramobject) {int i;if (paramobject = = null) for (i = this.size-1; I >= 0; i.) if (this. Elementdata[i] = = null) return i;elsefor (i = this.size-1; I >= 0; i.) if (Paramobject.equals (this.elementdata[i)) ret Urn i;return-1;}

The two methods are analyzed together because there are many similarities between the two methods in terms of functionality and implementation, where INDEXOF () returns the subscript position where the element is located, traversing backward from the first element, and the LastIndexOf () method is the opposite, It is the last element of the list that begins to traverse and then returns the position of the last element in the distance.

Take the IndexOf (Object) method as an example, the source code can see its implementation is this: if the incoming parameter object is not empty, then start to walk through the list object from beginning to end, if the traversed element object is not empty, then the object to be compared with the incoming, If the value of the comparison is equal then it returns the subscript position of the comparison, and returns 1 if the element is not found;

E:get (int)

Public E get (int paramint) {Rangecheck (paramint); return Elementdata (Paramint);} E elementdata (int paramint) {return this.elementdata[paramint];} private void Rangecheck (int paramint) {if (Paramint < this.size) Return;throw new Indexoutofboundsexception ( Outofboundsmsg (Paramint));}

This method returns the value of the list in the corresponding position according to the index subscript, which first determines whether the passed-in argument is valid by using the Rangcheck (int) method, and then returns its value through the Elementdata (int) method. But we can see that it actually gets the corresponding value directly from the array subscript.

F:clear ()

  

public void Clear () {This.modcount + = 1;for (int i = 0; i < this.size; ++i) This.elementdata[i] = Null;this.size = 0;}

Clear () as the name implies is to empty the list, its implementation logic is very simple to traverse and then set the value of each position to null, and the length of the list is set to 0;

G: Delete Element

  

public E remove (int paramint) {Rangecheck (paramint); This.modcount + = 1;Object Localobject = Elementdata (paramint); int i = this.size-paramint-1;if (i > 0) system.arraycopy (this.elementdata, param Int + 1, this.elementdata,paramint, i); this.elementdata[(--this.size)] = Null;return localobject;} public boolean remove (Object paramobject) {int i;if (paramobject = = null) for (i = 0; i < this.size; ++i) {if (This.elem ENTDATA[I]! = null) continue;fastremove (i); return true;} Elsefor (i = 0; i < this.size; ++i) {if (! ( Paramobject.equals (This.elementdata[i])) continue;fastremove (i); return true;} return false;} private void Fastremove (int paramint) {This.modcount + = 1;int i = this.size-paramint-1;if (i > 0) system.arraycopy (t His.elementdata, Paramint + 1, this.elementdata,paramint, i); this.elementdata[(--this.size)] = null;} 

The first method, remove (int), is to delete the element by the subscript position, first to determine whether the argument is valid, then to get the element value of the subscript position, to move the position of each element by copying, and finally to null the last face element of the original list, returning the deleted object The second method is to remove the object directly from the first element, start the traversal, if the traversal to delete returns True, if the element does not exist to return false, the third method is to delete the elements of the method independent of the subscript to delete the object element.

H: adding elements

  

Public boolean Add (E ParamE) {ensurecapacityinternal (this.size + 1); this.elementdata[(this.size++)] = Parame;return true;} public void Add (int paramint, E paramE) {rangecheckforadd (paramint); ensurecapacityinternal (this.size + 1); System.arraycopy (This.elementdata, Paramint, This.elementdata,paramint + 1, this.size-paramint); this.elementData[ Paramint] = parame;this.size + = 1;} public boolean addall (collection<? extends e> paramcollection) {object[] Arrayofobject = Paramcollection.toarray ( ); int i = arrayofobject.length;ensurecapacityinternal (this.size + i); System.arraycopy (arrayofobject, 0, This.elementdata, this.size, i); This.size + = I;return (i! = 0);} public boolean addall (int paramint, collection<? extends e> paramcollection) {rangecheckforadd (paramint); object[ ] Arrayofobject = Paramcollection.toarray (); int i = arrayofobject.length;ensurecapacityinternal (this.size + i); int j = th Is.size-paramint;if (J > 0) system.arraycopy (this.elementdata, Paramint, This.elementdata,paRamint + i, j); System.arraycopy (arrayofobject, 0, This.elementdata, paramint, i); This.size + = I;return (i! = 0);}

The first and second ways to add an element, the third and the fourth method is to add a collection to the list, the first method is to first check whether the size of the list is appropriate, and then directly at the end of the list to add the upper element. The second way is to add the element object at the established position, except to check the subscript position and the capacity of the list, which is to move the position of each element back and leave the vacated position to the object we need to insert. The third method and the fourth method implement and the first second type, just turn an element into a collection.

I:contains (Object)

Public Boolean contains (Object paramobject) {return (IndexOf (paramobject) >= 0);}

The method is to see if there is an element, first to get the position of the element in the list, if the position exists to say that contains the element.

4. Other (summary)

ArrayList is the basis of the array to add some of the methods we have often used in the development, but some methods are not efficient, we can in the specific development process, depending on the situation and whether the need to rewrite. But it provides a lot of methods that are basically enough for us to use. Just through the source code to understand some of its underlying methods of implementation.

Java collection of ArrayList source code analysis

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.