Java Set framework ArrayList source Analysis (i) _java

Source: Internet
Author: User

ArrayList the underlying maintenance is a dynamic array in which each ArrayList instance has a capacity. This capacity refers to the size of the array that is used to store the list elements. It is always at least equal to the size of the list. As you add elements to the ArrayList, the capacity increases automatically.

ArrayList is not synchronized (that is, not thread safe), if multiple threads access a ArrayList instance at the same time, and at least one of the threads modifies the list from the structure, then it must remain externally synchronized, in a multithreaded environment, You can use the Collections.synchronizedlist method to declare a thread-safe ArrayList, for example:
List arraylist = collections.synchronizedlist (New ArrayList ());
below through the ArrayList source to analyze its principle.
1, the construction method of ArrayList: ArrayList provides three different ways to construct
1) ArrayList () constructs an empty list with an initial capacity of 10.
2) ArrayList (int initialcapacity) constructs an empty list with the specified initial capacity.
3 ArrayList (collection<? extends e> c) constructs a list of elements that contain the specified Collection, sorted in the order in which they are returned by the Collection iterator.

The source code is as follows:

Private transient object[] elementdata;

Public ArrayList (int initialcapacity) {

  super ();

  if (initialcapacity < 0)

    throw new IllegalArgumentException ("illegal Capacity:" + initialcapacity);

  This.elementdata = new Object[initialcapacity]; Generates an array of type object of length 10

 } public

 

 

 ArrayList () {This

  (10); Call ArrayList (int i)

 }<br><br > Public

 ArrayList (collection< extends e> c) {

    elementdata = C.toarray ();  Returns the array size = Elementdata.length that contains all the elements in this collection

  ;

  C.toarray might (incorrectly) not return object[] (= 6260652)

  if (Elementdata.getclass ()!= object[].class) 
   elementdata = arrays.copyof (elementdata, size, object[].class); Copies the specified array, returning an array of type object containing the same element and length.

 

When a constructor with no parameters ArrayList () generates a collection object, it is actually called ArrayList (int initialcapacity) at the bottom of the construct method to produce an array of type object of length 10. When a construction method with a collection type parameter is adopted, an array of object types containing the same elements and lengths is generated at the bottom.

2, Add method: ArrayList provides two add methods for adding elements
1) Add (e E), Adds the specified element to the tail of this list.
2) Add (int index, e e) Inserts the specified element into the list at the specified location. Move the element (if any) that is currently at that position to the right and all subsequent elements (index 1) to private int size;

 public boolean add (E e) {ensurecapacity (size + 1);//enlarge array capacity elementdata[size++]  = e;

  Adds element E to the object array with subscript size, and executes size++ return true;

    public void Add (int index, E element) {if (Index > Size | | Index < 0)//If you specify that the subscript you want to insert exceeds the array capacity or the specified subscript is less than 0, throw the exception

 

  throw new Indexoutofboundsexception ("Index:" +index+ ", Size:" +size); Ensurecapacity (size+1); Enlarge array Capacity system.arraycopy (Elementdata, index, elementdata, index + 1,size-index); Copies an array from the specified source array, starting at the specified location and ending at the specified position in the destination array.                                          <br>//Elementdata---Source array index---the starting position in the source array <br>                                          Elementdata---target array index+1---the starting position in the target array <br> Size-index---The number of array elements to copy elementdata[index] = element;

  The element to be added is placed at the specified array subscript size++; }

public void ensurecapacity (int mincapacity) {

  modcount++;

  int oldcapacity = Elementdata.length; The capacity of the original array

  if (Mincapacity > Oldcapacity) {

    Object olddata[] = elementdata;

    int newcapacity = (oldcapacity * 3)/2 + 1; Defines the capacity of the new array, 1.5 times times the original array capacity of +1

      if (newcapacity < mincapacity)

    newcapacity = mincapacity;

      Mincapacity is usually close to size, and so is a win:

      Elementdata = arrays.copyof (Elementdata, newcapacity);//Copy The specified array, which returns the capacity of the new array as Newcapacity

  }

  }

If the collection has more than 10 elements added, then the ArrayList bottom will be reborn into an array, 1.5 times times the length of the original array +1, and copy the elements from the original array into the new array, and subsequent additions will be placed in the new array, when the length of the new array cannot accommodate the newly added elements. Repeat the process. This is how the collection adds elements to the implementation principle.

3, Get Method:
1 Get (int index) returns the element at the specified position in this list.

Public E get (int index) {
  Rangecheck (index);//Check whether the incoming specified subscript is legal return
 
  (E) Elementdata[index]; Returns the array element labeled index for the array

  }
private void Rangecheck (int index) {
  if (index >= size)//If the incoming subscript is greater than or equal to the capacity of the collection, throw the exception
    throw new Indexoutofboundsexception (
    "Index: +index+", Size: "+size);

  }

4. Remove Method:
1 E Remove (int index) removes the element from the specified position in this list. Moves all subsequent elements to the left (the index is reduced by 1).
2 The Boolean remove (Object O) removes the first occurrence of the specified element (if present) in this list. If the list does not contain this element, the list does not make changes and returns a Boolean value.

Public E-Remove (int index) {rangecheck (index);//Check that the specified subscript is legal modcount++; E OldValue = (e) elementdata[index]; Gets the array element int nummoved = Size-index-1 for the specified subscript; The number of elements to move if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, Index, nummoved); Move array element elementdata[--size] = null;

  Let GC does its work return oldValue; public boolean remove (Object o) {if (o = = null) {//If the passed-in argument is null for (int index = 0; index < size;

      dex++) if (elementdata[index] = = null) {//Remove the first occurrence of NULL fastremove (index);

    return true; } else {for (int index = 0; index < size; index++) if (O.equals (Elementdata[index)) {Fastremov

      E (index);

    return true;

  return false;

    The private void Fastremove (int index) {//Removes the element at the specified position and implements a method similar to the remove (int i) modcount++;

    int nummoved = size-index-1; if (nummoved > 0) system.arraycopy (elementdata, index+1, ElemEntdata, index, nummoved); Elementdata[--size] = null;

 Let GC does its work}

5. Clone method:
1) Object clone (), which returns a shallow copy of this ArrayList instance (the elements themselves are not copied).

Public Object Clone () {
  try {
    arraylist<e> v = (arraylist<e>) super.clone ();// The Clone method that calls the object class returns a ArrayList object
    v.elementdata = arrays.copyof (elementdata, size);//Copy target array
    v.modcount = 0;
    return v;

  } catch (Clonenotsupportedexception e) {

    //This shouldn ' t happen, since we are cloneable throw

    new Internalerror ();

  }

  }

Above through the ArrayList part of the key source of analysis, know the ArrayList the implementation of the principle of the bottom, about the ArrayList source has the following several points summary:
1 The bottom of the ArrayList is based on an array, you can find the target element accurately, so the search efficiency is high, but adding or removing elements involves a large number of elements in the position of moving, inefficient.
2) ArrayList provides three different construction methods, constructor without parameters by default generates an array of type object of length 10 at the bottom, when the number of elements added in the collection is greater than 10, the array expands automatically, generating a new array and placing the elements of the original array in the new array.
3 The Ensurecapacity method expands the array, it generates a new one, which is 1.5 times times +1 of the original array, and repeats the process as it adds elements to the ArrayList and the array length does not meet the need.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.