Java collection Source analysis: vector source Analysis

Source: Internet
Author: User
Tags addall array length arrays constructor int size thread tostring

Vector Introduction

Vector is also based on the array, is a dynamic array, its capacity can automatically grow.

LinkedList is JDK1.0 introduced, many of its implementation methods are added to the synchronization statements, so it is thread-safe (in fact, only relatively safe, sometimes to join the synchronization statements to ensure thread security), can be used in multithreaded environments.

LinkedList has no thread serializable interface, so it does not support serialization, realizes the Cloneable interface, can be cloned, implements the Randomaccess interface and supports fast random access.

Vector Source Analysis

The source code for the vector is as follows (add a more detailed note):

Package java.util; public class Vector<e> extends abstractlist<e> implements List<e>, Randomaccess, Cloneab    
       
    Le, java.io.Serializable {//save array of data in vector protected object[] elementdata;    
       
    The number of actual data protected int elementcount;    
       
    Capacity growth coefficient protected int capacityincrement;    
       
    The sequence version number of the vector is private static final long serialversionuid = -2767605614048989439l; The Vector constructor.    
    The default capacity is 10.    
    Public Vector () {this (10);    
    //Specifies the constructor of the vector capacity size public vector (int initialcapacity) {This (initialcapacity, 0); //Specifies the constructor for vector "capacity size" and "growth factor" public vector (int initialcapacity, int capacityincrement)    
        {super ();    
                    if (initialcapacity < 0) throw new illegalargumentexception ("illegal Capacity:" +                           initialcapacity);    
        Creates a new array with an array capacity of initialcapacity This.elementdata = new Object[initialcapacity];    
    Set capacity growth factor this.capacityincrement = capacityincrement;    
    //Specifies the vector constructor for the collection. Public Vector (COLLECTION< extends e> c) {//Get an array of "set (c)" and assign it to elementdata Elementdata = C    
        . ToArray ();    
        Set array length elementcount = elementdata.length; C.toarray might (incorrectly) not return object[] (= 6260652) if (Elementdata.getclass ()!= Object[].clas    
    s) elementdata = arrays.copyof (Elementdata, Elementcount, Object[].class);    
        To copy all elements of an array vector to the array anarray public synchronized void Copyinto (object[] anarray) {    
    System.arraycopy (elementdata, 0, Anarray, 0, Elementcount);    
///Set the current capacity value to = number of actual elements public synchronized void TrimToSize () {        modcount++;    
        int oldcapacity = Elementdata.length;    
        if (Elementcount < oldcapacity) {Elementdata = arrays.copyof (Elementdata, Elementcount);    
        }//Confirm Help function for vector capacity private void ensurecapacityhelper (int mincapacity) {    
        int oldcapacity = Elementdata.length;    
        Increase capacity when vector capacity is insufficient to accommodate all current elements.    
        If the capacity increment coefficient is >0 (ie capacityincrement>0), the capacity is increased by one-fold when the capacityincrement//otherwise.    
            if (Mincapacity > Oldcapacity) {object[] olddata = elementdata;    
                int newcapacity = (capacityincrement > 0)?    
            (Oldcapacity + capacityincrement): (oldcapacity * 2);    
            if (Newcapacity < mincapacity) {newcapacity = mincapacity;    
        } Elementdata = arrays.copyof (Elementdata, newcapacity);    
   }//Determine the capacity of the vector. Public synchronized void ensurecapacity (int mincapacity) {//vector change statistics +1 modcount++;    
    Ensurecapacityhelper (mincapacity);    
        }//Set capacity value of newsize public synchronized void setSize (int newsize) {modcount++;    
            if (NewSize > Elementcount) {//If newsize is greater than the vector capacity, resize the vector.    
        Ensurecapacityhelper (newsize); else {//if "newsize is less than/equal to vector capacity", the element that starts the newsize position is set to NULL for (int i = newsize; I & Lt Elementcount;    
            i++) {Elementdata[i] = null;    
    } elementcount = newsize;    
    //returns "The total capacity of the vector" public synchronized int capacity () {return elementdata.length; //Returns the "vector's actual size", that is, the number of elements in vector public synchronized int size () {return eleme    
    Ntcount; }//Judge vector is an empty public synchronized Boolean IsEmpty () {return elementcount = 0; //Returns the "enumeration" public enumeration<e> elements () {//) for all elements in vector, implemented by anonymous class    
       
            Enumeration return new enumeration<e> () {int count = 0;    
            Whether there is a next element public boolean hasmoreelements () {return count < Elementcount; //Get Next element public E Nextelement () {synchronized (vector.this) {if (Count < Elementcount) {return (E) elementdata[c    
                    Ount++];    
            } throw new Nosuchelementexception ("Vector enumeration");    
    }    
        }; //Returns whether the vector contains objects (O) public boolean contains (object o) {return indexOf (o, 0) >= 0;    
    ///Find the element backward from the index position (o).    
            If found, returns the index value of the element; otherwise, returns-1 public synchronized int indexOf (Object o, int index) {if (o = = null) {    
            If the lookup element is null, it finds the null element and returns its corresponding ordinal for (int i = index; i < Elementcount i++)    
        if (elementdata[i]==null) return i;     
            else {//If the lookup element is not NULL, it finds the element and returns its corresponding ordinal for (int i = index; i < Elementcount i++)    
        if (O.equals (Elementdata[i])) return i;    
    } return-1;    
    //Find and return the index value of Element (O) in vector public int indexOf (Object o) {returns indexOf (o, 0); //Look for the Element (O) from the back forward.    
    and returns the index of the element public synchronized int LastIndexOf (Object o) {return LastIndexOf (o, elementCount-1); //Look for the Element (O) from the back forward. The starting position is the number of index numbers from the front to the back;//If found, returns the indexed value of the element;1.  public synchronized int LastIndexOf (Object o, int index) {if (index >= elementcount) throw    
       
        New Indexoutofboundsexception (index + ">=" + elementcount);    
            if (o = = null) {//If the lookup element is null, the reverse finds the null element and returns its corresponding ordinal for (int i = index; I >= 0; i--)    
        if (elementdata[i]==null) return i;    
            else {//If the lookup element is not NULL, reverse-Locate the element and return its corresponding ordinal for (int i = index; I >= 0; i--)    
        if (O.equals (Elementdata[i])) return i;    
    } return-1;    
    //Returns the element of the index position in the vector.    
            If the index month knot, then throws an exception public synchronized E elementat (int index) {if (index >= elementcount) {    
        throw new ArrayIndexOutOfBoundsException (index + ">=" + elementcount);    
    Return (E) Elementdata[index];    
       
  }  Gets the first element in the vector.    
    If it fails, throw an exception! Public synchronized E firstelement () {if (Elementcount = 0) {throw new Nosuchelementexcepti    
        On ();    
    Return (E) elementdata[0];    
    //Gets the last element in the vector.    
    If it fails, throw an exception! Public synchronized E lastelement () {if (Elementcount = 0) {throw new Nosuchelementexceptio    
        N ();    
    Return (E) elementdata[elementcount-1]; //Set the element value for index position is obj public synchronized void Setelementat (E obj, int index) {if (i    
                                 Ndex >= Elementcount) {throw new ArrayIndexOutOfBoundsException (index + ">=" +    
        Elementcount);    
    } Elementdata[index] = obj;    
        }//delete element public synchronized void Removeelementat (int index) {modcount++) at the index position; if (Index >= eleMentcount) {throw new ArrayIndexOutOfBoundsException (index + ">=" +    
        Elementcount);    
        else if (Index < 0) {throw new arrayindexoutofboundsexception (index);    
        int j = elementcount-index-1;    
        if (J > 0) {system.arraycopy (elementdata, index + 1, elementdata, index, J);    
        } elementcount--; Elementdata[elementcount] = null; * To let the GC do it work/////Insert Element (obj) public synchronized void Insertelementat at the index position (    
        E obj, int index) {modcount++;    
                                 if (Index > Elementcount) {throw new ArrayIndexOutOfBoundsException (index    
        + ">" + elementcount);    
        } ensurecapacityhelper (Elementcount + 1); System.arraycopy (Elementdata, index, Elementdata, index + 1, elementcount-index);    
        Elementdata[index] = obj;    
    elementcount++;    
        ///Add "element obj" to the vector end public synchronized void addelement (E obj) {modcount++;    
        Ensurecapacityhelper (Elementcount + 1);    
    elementdata[elementcount++] = obj;    
    Find and delete element obj in vector. 
Returns true if successful, otherwise, returns false.    
        More highlights of this column: Http://www.bianceng.cn/Programming/Java/public synchronized boolean removeelement (Object obj) {    
        modcount++;    
        int i = indexOf (obj);    
            if (I >= 0) {removeelementat (i);    
        return true;    
    return false;    
        }//Remove all elements in vector public synchronized void removeallelements () {modcount++;    
       
        Set all elements in the vector to NULL for (int i = 0; i < elementcount i++) elementdata[i] = null;    
    Elementcount = 0;    
     }  
    Clone function public synchronized Object clone () {try {vector<e> v = (vector& Lt    
            e>) Super.clone ();    
            Copies all elements of the current vector into v v.elementdata = arrays.copyof (Elementdata, Elementcount);    
            V.modcount = 0;    
        return v;    
            catch (Clonenotsupportedexception e) {//This shouldn ' t happen, since we are cloneable    
        throw new Internalerror (); }//returns Object array public synchronized object[] ToArray () {return arrays.copyo    
    F (Elementdata, elementcount); //Returns the template array for the vector.    
        The so-called template array, that is, you can set T to any data type public synchronized <T> t[] ToArray (t[] a) {//If the size of the array a < the number of vector elements;    
            A new t[] array is created, and the array size is the number of elements of the vector, and all vectors are copied to the new array if (A.length < Elementcount) Return (t[]) arrays.copyof (Elementdata, Elementcount, A.getclass ());    
    If the size of the array a >= the number of elements of the vector;//The entire element of the vector is copied to array a.    
       
        System.arraycopy (elementdata, 0, a, 0, elementcount);    
       
        if (A.length > Elementcount) a[elementcount] = null;    
    return A;     
            //Gets the element public synchronized E get (int index) {if (index >= elementcount) of the index position    
       
        throw new ArrayIndexOutOfBoundsException (index);    
    Return (E) Elementdata[index]; //Set the value of index position to element.    
            and returns the original value of the index position public synchronized E set (int index, e element) {if (Index >= elementcount)    
       
        throw new ArrayIndexOutOfBoundsException (index);    
        Object oldValue = Elementdata[index];    
        Elementdata[index] = element;    
    Return (E) OldValue;    
    ///Add "element e" to the vector last. Public synchronized Boolean Add (E e) {modcount++;   
        Ensurecapacityhelper (Elementcount + 1);    
        elementdata[elementcount++] = e;    
    return true;    
    //Remove element O public boolean remove (Object o) in vector {return removeelement (o); ///add element elements public void Add (int index, E element) {Insertelementat (elem) at the index position    
    ENT, index);     
        //Deletes the element at the index position and returns the original value of the index position public synchronized E Remove (int index) {modcount++;    
        if (index >= elementcount) throw new ArrayIndexOutOfBoundsException (index);    
       
        Object oldValue = Elementdata[index];    
        int nummoved = elementcount-index-1; if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, index, n    
        ummoved); Elementdata[--elementcount] = null;    
    Let GC does its work return (E) OldValue;  }  
       
    Empty vector public void clear () {removeallelements ();    
        //Returns whether the vector contains the collection C public synchronized Boolean containsall (collection<?> c) {    
    return Super.containsall (c);    
        ///Add collection C to the vector public synchronized Boolean addall (collection<? extends e> c) {    
        modcount++;    
        Object[] A = C.toarray ();    
        int numnew = A.length;    
        Ensurecapacityhelper (Elementcount + numnew);    
        Copies all elements of the set C to the array Elementdata system.arraycopy (A, 0, Elementdata, Elementcount, numnew);    
        Elementcount + = numnew;    
    return numnew!= 0; }//Delete all elements of Set C public synchronized Boolean RemoveAll (collection<?> c) {return    
    Super.removeall (c); }//delete elements in non-set C public synchronized Boolean retainall (collection<?> c) {Retu RN Super.retaiNall (c); ///Starting at the index position, add collection C to the vector public synchronized boolean addall (int index, collection<? exten    
        DS e> c) {modcount++;    
       
        if (Index < 0 | | | index > Elementcount) throw new ArrayIndexOutOfBoundsException (index);    
        Object[] A = C.toarray ();    
        int numnew = A.length;    
       
        Ensurecapacityhelper (Elementcount + numnew);    
        int nummoved = Elementcount-index;    
       
        if (nummoved > 0) system.arraycopy (elementdata, index, elementdata, index + numnew, nummoved);    
        System.arraycopy (A, 0, Elementdata, index, numnew);    
        Elementcount + = numnew;    
    return numnew!= 0;     
    //Returns whether two objects are equal public synchronized Boolean equals (object o) {return super.equals (o); //computed hash value public synchronized int hashcode () {return super.hashcode();    
    }//Invoke the parent class's ToString () public synchronized String ToString () {return super.tostring (); //Get a subset of Fromindex (including) to Toindex (not included) in the vector, public synchronized list<e> sublist (int    
    Fromindex, int toindex) {return collections.synchronizedlist (Super.sublist (Fromindex, Toindex), this); }//remove element fromindex to Toindex in vector protected synchronized void removerange (int fromindex, int t    
        Oindex) {modcount++;    
        int nummoved = Elementcount-toindex;    
       
        System.arraycopy (Elementdata, Toindex, Elementdata, Fromindex, nummoved);    
        Let GC does its work int newelementcount = Elementcount-(toindex-fromindex);    
    while (Elementcount!= newelementcount) elementdata[--elementcount] = null; }//Java.io.Serializable write function private synchronized VOID WriteObject (Java.io.ObjectOutputStream s) throws java.io.IOException {S.defaultwriteobject (); }    
}

Some summary

Vector source implementation of the overall and ArrayList similar, on the vector source, gives the following summary:

1. Vector has four different methods of construction. The capacity of the parameterless construction method is the default value of 10, and only the capacity-building method will increase the capacity (from the source to see the effect of capacity growth, the 2nd will be detailed on capacity growth) Ming set to 0.

2, attention to expand the capacity of the method Ensurecapacityhelper. As with ArrayList, the vector calls this method to ensure sufficient capacity each time an element is added (perhaps 1, or possibly a group). When the capacity is insufficient to accommodate the current number of elements, let's see if the capacity growth parameter Capacityincrement in the constructor is 0, if not 0, set the new capacity for capacity plus capacity, and if 0, set the new capacity to twice times the old capacity, If the new capacity is not sufficient, the direct new capacity is set to the incoming parameter (that is, the desired capacity), and then the element is also copied to the new array using the Arrays.copyof () method.

3, many methods have joined the synchronized synchronization statement, to ensure thread safety.

4, also in the search for a given element index value, and so on, the source code will be the value of the element is divided into null and NOT NULL two cases of processing, vector also allows the element is null.

5, many other places are similar to the ArrayList, Vector is now basically no longer used.

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.