Java ArrayList Implementation Example explanation _java

Source: Internet
Author: User
Tags addall arrays int size serialization throw exception

ArrayList Overview:

ArrayList is based on the array, is a dynamic array, its capacity can automatically grow, similar to the C language Dynamic application memory, dynamic growth of memory.

ArrayList is not thread-safe and can only be used in a single-threaded environment, the collections.synchronizedlist (List L) function can be considered in a multithreaded environment to return a thread-safe ArrayList class. You can also use the Copyonwritearraylist class under the concurrent concurrency package.

ArrayList implements the serializable interface, so it supports serialization, can realize the Randomaccess interface through the serialization transmission, supports the fast random access, in fact is the fast access through the subscript serial number, realizes the Cloneable interface, can be cloned.

Each ArrayList instance has a capacity, which is the size of the array 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. Automatic growth will result in a new copy of the data to the array, so if you can predict the amount of data, you can specify its capacity when constructing ArrayList. Before adding a large number of elements, the application can also use the Ensurecapacity action to increase the capacity of the ArrayList instance, which reduces the number of incremental redistribution.

Note that this implementation is not synchronized. If more than one thread accesses a ArrayList instance at the same time, and at least one of the threads modifies the list from the structure, it must maintain an external synchronization.

The following Java ArrayList to make a record and summary it

The public class Arraylist<e> {
  /**
   * Stores the elements of the collection * * *
  /private transient object[] elementdata;
  /** element Size *
  /private int size;

Defines a generic class, an object array and a private variable to record the number of elements of the collection, the original text more than a private variable, I do not know what to use, the author did not explain also did not mention, I did not use also nothing

/**
   * Initializes
   * @param initialcapacity/public
  ArrayList (int initialcapacity) {
    super ()
    according to the specified size; if (initialcapacity<=0) {
      //Throw exception
      throw new IllegalArgumentException ("Initialization parameter cannot be less than 0");
    else{
      //initialization array
      this.elementdata=new object[initialcapacity];
    }
  /**
   * Default initialization
   /public
  ArrayList () {this
    ;
  }
  /**
   * Based on a collection class initialize
   * @param c A class that must inherit the Collection interface
  /public ArrayList (COLLECTION<? extends E > C) {
    //initialization of
    Elementdata=c.toarray ();
    Size=elementdata.length;
    If not an array of any type, convert the OBJEC type
    if (Elementdata.getclass ()!= object[].class) {
      elementdata=arrays.copyof ( Elementdata,size, Object[].class);
    }
  

3 initialization methods, initialization of the array based on the default size, initialization of a given size, and passing of a class that inherits the collection collection interface for conversion assignment initialization

/**
   * Capacity Collection
   * @param mincapacity
  /public void ensurecapacity (int mincapacity) {
    /** the current array size * *
    int oldcapacity = elementdata.length; 
    if (Mincapacity > Oldcapacity) {
      /**
       * OldData is not in use, but this is a reason for memory management and the arrays.copyof () method is not thread safe
       * OldData references elementdata This variable in the life cycle of if, so it is not recycled by GC
       * when the arrays.copyof () method copies Elementdata to Newcapacity, Can prevent new memory or other threads from allocating memory is elementdata memory is overrun modified
       * When the end is left If,olddata cycle End is recycled *
       *
      Object olddata[] = Elementdata ; 
      int newcapacity = (oldcapacity * 3)/2 + 1; Add 50%+1
        if (newcapacity < mincapacity) 
          newcapacity = mincapacity; 
     Use arrays.copyof to copy the elements of the collection and generate a new array
     elementdata = arrays.copyof (Elementdata, newcapacity); 
    } 
  

This is a core method, the expansion of the set, in fact, is the expansion of the array, the size of the Mincapacity collection, to compare and determine whether the expansion, using the arrays.copyof () method for expansion,

The original text is explained in detail, this method copies the contents of the first parameter into a new array, the size of the array is the second parameter, and returns a new array, with a detailed comment on the olddata variable.

 /**
   * Check whether the index is out of bounds * @param index */
  private void Rangecheck (int index) {
    if (Index > Size | | Index < 0) {
      throw new indexoutofboundsexception ("Subscript exceeded, Index:" + index + ", Size:" +size);
    }
  

Whether a subscript retrieval is out of 1/**

* Add Element
   * Adds the specified element to the end of the collection
   * @param e added element
   * @return
   /Public
  Boolean Add (e) {
    Ensurecapacity (size+1);
    elementdata[size]=e;
    size++;
    return true;
  }

Add elements, first expand, in the assignment, and then the element plus one, note that the Size+1 field size does not add one, here is the arithmetic operation, so after the need for self-increase

/**
   * Add element
   * add element to specified location
   * @param index specified indexed subscript
   * @param element element
   * @return
  /Public Boolean Add (int index, E element) {
    Rangecheck (index);
    Ensurecapacity (size+1);
    The element that starts at the index position in the Elementdata, the length is size-index, 
    //copies to the new Elementdata array starting with the subscript index+1 position. 
    //Move right one position to the element currently at that location and all subsequent elements.
    system.arraycopy (elementdata, Index, Elementdata, index+1, size-index);
    elementdata[index]=element;
    size++;//element plus one return
    true;
  }

The difference here is system.arraycopy (Elementdata, Index, Elementdata, index+1, Size-index);

This is a C internal method, the detailed text has the explanation, here does not say, this also is the entire ArrayList core place, also arrays.copyof () the internal realization principle

/**
   * Add all elements
   * Add all the elements in the collection to the end of this list according to the order of the elements returned by the iterator for the specified collection. 
   * @param c
   * @return
  /public boolean AddAll (Collection < extends e>c) {
    object[] Newelement=c.toarray ();
    int elementlength=newelement.length;
    Ensurecapacity (size+elementlength);
    Starting with the subscript for newelement 0, elementlength elements, elementdata size subscript 
    system.arraycopy (newelement, 0, elementdata, size, Elementlength);
    Size+=elementlength;
    return elementlength!=0;
  }

Basically, other methods are handled differently depending on the situation, such as passing the data object through the interface and acquiring the length for expansion, and copying the data using system,arraycopy into the new array

/** * Specify the location, add all elements * @param index * @param c Inserts the element set * @return/public boolean addall (int index , collection<? Extends e> c) {if (Index > Size | | Index < 0) {throw new Indexoutofboundsexception ("index:" + index + "
    , Size: "+size);
    } object[] Newelement=c.toarray ();
    int elementlength=newelement.length;
    Ensurecapacity (size+elementlength);
    int nummoved=size-index; Determines whether the insertion position is in the middle of an array if (nummoved>0) {//moves all elements after the index insertion position backward//elementdata The nummoved element starting with the index subscript into the ELEMENTD
    ATA index+elementlength Location system.arraycopy (elementdata, Index, Elementdata, Index+elementlength, numMoved);  ///Add the elementlength elements from the newelement to the beginning of the Elementdata index system.arraycopy (newelement, 0, Elementdata, index, 
    Elementlength); 
    Size + = Elementlength;
  return elementlength!= 0;
    /** * Specifies subscript assignment * @param index * @param element * @return/public E set (int index,e element) {Rangecheck (index);
    e oldelement= (e) elementdata[index];
    Elementdata[index]=element;
  return oldelement;
    /** * According to the subscript value * @param index * @return/public E get (int index) {rangecheck (index);
  Return (E) Elementdata[index];
    /** * Removes element * @param index/Public E-Remove (int index) {rangecheck (index) by subscript;
    e oldelement= (e) elementdata[index];
    /** the number of elements to be removed after the subscript/int nummoved=size-index-1;
    If you are moving within the array range if (nummoved>0) system.arraycopy (Elementdata, index+1, Elementdata, Index, nummoved);
    removing elementdata[--size]=null;
  return oldelement; /** * Remove * @param obj * @return/public boolean remove (Object obj) {//arraylist allows null to be stored, so
           To be judged processing if (Obj==null) {for (int index=0;index<size;index++) {if (elementdata[index]==null) {
           Remove (index);
        return true;
}}else{for (int index=0;index<size;index++) {        if (Obj.equals (Elementdata[index])) {Remove (index);
        return true;
  }} return false; /** * Removes the specified range of elements from the subscript * @param fromindex start * @param toindex end/protected void removerange (int from
    Index, int toindex) {Rangecheck (fromindex);
    Rangecheck (Toindex); 
    The number of elements to move int nummoved = Size-toindex;
    Move the elements behind the Toindex to the Fromindex system.arraycopy (Elementdata, Toindex, Elementdata, Fromindex, nummoved);
    The number of elements to be removed int newsize=size-(TOINDEX-FROMINDEX);
    while (size!=newsize) {elementdata[--size]=null;
    }/** * Adjusts the array capacity to the actual capacity/public void trimtosize () {int leng=elementdata.length;
      if (Size<leng) {object[] old=elementdata;
    Elementdata=arrays.copyof (elementdata, size);
  }/** * Converts the collection elements to a group * @return/public object[] ToArray () {return arrays.copyof (elementdata, size); } public <t>t[] ToArray (t[] a) {if (A.LEngth<size) {return (t[]) arrays.copyof (Elementdata,size, A.getclass ());
     ///Copy the collection elements into a array of system.arraycopy (Elementdata, 0, a, 0, size);
       if (a.length > Size) {for (int index=size;index<a.length;index++) {A[index] = null; 
  } return A; }

Basically are the operation of the array and the use of the C method of assignment, and so on, detailed can see the original text, in addition to that private variable also not many problems, the code can be perfect operation, this Lee should pay attention to and the difficulty will be system,arraycopy and arrayist.copy () These 2 methods
And in the expansion method olddata the use of this variable, this variable is really good, at first I do not know why to use this, at the end of the original text will be interpreted.

The above is a small series to introduce the Java ArrayList implementation examples to explain, I hope to help you, if you have any questions welcome to my message, small series will promptly reply to everyone, here also thank you for your support cloud Habitat community site!

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.