Java Collection Learning (vi) vector detailed introduction (source analysis) and use examples

Source: Internet
Author: User
Tags addall array length arrays constructor contains empty int size object object

After learning ArrayList and LinkedList, we went on to study vector. Learning the same way as before, the vector has a general understanding, and then learn its source, and finally through the example to learn to use it.

Part 1th Vector Introduction

Vector Introduction

Vectors are vector queues, which are classes added by the JDK1.0 version. Inherits from Abstractlist, implements the list, randomaccess, cloneable these interfaces.
Vector inherits the Abstractlist and realizes the list; therefore, it is a queue, supporting the relevant add, delete, modify, traverse and other functions.
Vector implements the Randmoaccess interface, which provides a random access function. Randmoaccess is a list implemented in Java to provide quick access to the list. In vector, we can quickly get the element object by the ordinal of the element, which is the fast random access.
Vector implements the Cloneable interface, which is the implementation of the Clone () function. It can be cloned.

Unlike ArrayList, operations in vectors are thread-safe, but vectors do not support serialization, that is, the Java.io.Serializable interface is not implemented.

The inheritance relationship of vectors

Java.lang.Object
        java.util.abstractcollection<e>
              java.util.abstractlist<e>
                    Java.util.vector<e> public
     
class vector<e>
    extends abstractlist<e>
    implements List <e>, Randomaccess, cloneable, java.io.Serializable {}

The relationship between vector and collection is as follows:

The constructor of a vector

Vector has 4 constructors
//default constructors
vector ()
     
//capacity is the default capacity size of the vector. When the capacity increases due to increased data, the capacity is increased by one times per volume.
vector (int capacity)
     
//capacity is the default capacity size of the vector, Capacityincrement is the increment for each vector capacity increase.
vector (int capacity, int capacityincrement)
     
//create a vector vector containing Collection
(collection<? extends E > Collection)

Vector API

Synchronized Boolean Add (E object) void Add (int location, E object) Synchronized Boolean AddAll (collection< extends e> Collection) synchronized boolean addall (int location, collection<? ext
             Ends E> collection) synchronized void AddElement (E object) synchronized int capacity () void clear () Synchronized Object Clone () Boolean contains (object) Synchroni Zed Boolean Containsall (collection<?> Collection) synchronized void Copyinto (object[) elements) SYN           chronized E elementat (int location) enumeration<e> elements () synchronized void ensurecapacity (int minimumcapacity) Synchronized Boolean equals (object) synchronized E Firstele ment () E get (int location) synchronized int hashcode () synchronized int Dexof (Object object, int Location) int IndexOf (object) synchronized void Insertelementat (E object, int lo cation) Synchronized Boolean isempty () synchronized E lastelement () synchronized int lastin Dexof (Object object, int location) synchronized int LastIndexOf (object) synchronized E Remo ve (int location) Boolean remove (Object object) Synchronized Boolean RemoveAll (COLLECTION&LT;?&G T collection) synchronized void Removeallelements () Synchronized Boolean removeelement (object) synch 
ronized void Removeelementat (int location) Synchronized Boolean retainall (collection<?> Collection)
Synchronized e set (int location, E object) synchronized void Setelementat (E object, int location) synchronized void setSize (int length) synchronized int size () synchronized list<e> Subli St (int start, int end) synchronized <T> t[] ToArray (t[] contents) synchronized object[] ToArray () synchronized String ToString () synchronized void TrimToSize ()

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/

The 2nd part vector source analysis

To get a better idea of vector, the following is an analysis of the vector source code.

Package java.util; public class Vector<e> extends abstractlist<e> implements List<e>, Randomaccess, Cloneable, 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" the 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&LT; 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[].class)
    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.Array
    Copy (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 Vector capacity help function 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 vector capacity", the vector size is adjusted.
        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 < Elem Entcount;
            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 the vector is public synchronized int size () {return elementcount;
    //Determine if the vector is empty public synchronized Boolean IsEmpty () {return elementcount = 0;
        //Returns the "enumeration" public enumeration<e> elements () {//) for all elements in the vector is implemented through an anonymous class enumeration
     
            return new enumeration<e> () {int count = 0;
            Whether there is a next element public boolean hasmoreelements () {return count < Elementcount;
     }
            Gets the next element public E Nextelement () {synchronized (vector.this) {
                    if (Count < Elementcount) {return (E) elementdata[count++];
            } 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 element's "indexed value"; otherwise, returns-1. public synchronized int LastIndexOf (Object o, int index) {if (index >= elementcount) throw new Ind
     
        Exoutofboundsexception (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.E
        Quals (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 arrayindexoutofbounds
        Exception (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 nosuchelementexception ();
    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 nosuchelementexception ();
    Return (E) elementdata[elementcount-1]; //Set the element value for index position is obj public synchronized void Setelementat (E obj, int index) {if (Index >= ele Mentcount) {throw new ArrayIndexOutOfBoundsException (index + ">=" + ele
        Mentcount);
    } Elementdata[index] = obj;
     
    }Deletes the element public synchronized void Removeelementat (int index) {modcount++ of 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.
        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<e&gt
      ;) 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 NE
        W Internalerror (); }//returns Object array public synchronized object[] ToArray () {return arrays.copyof (Elementdata, ele
    Mentcount); //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[) Arra
     
        Ys.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 of the index position public synchronized E get (int index) {if (index >= elementcount) t
     
        Hrow 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) thr
     
        ow 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);
    {element public void Add (int index, E element) {Insertelementat (element, index) is added to the index position.
 }    
    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, nummoved)
        ; Elementdata[--elementcount] = null;
    Let GC does its work return (E) OldValue;
    //empty vector public void clear () {removeallelements (); The//returns whether the vector contains the collection C public synchronized Boolean containsall (collection<?> c) {return super.c
    Ontainsall (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.removeal
    L (c); //delete the elements in non-set C public synchronized Boolean retainall (collection<?> c) {return Super.retai
    Nall (c); ///Starting at the index position, add collection C to the vector public synchronized boolean addall (int index, COLLECTION&LT;? extends 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);
    }//Compute 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 vector (excluding) public synchronized list<e> sublist (int fromindex, int ToI
    Ndex) {return collections.synchronizedlist (Super.sublist (Fromindex, Toindex), this);
        //remove element fromindex to Toindex in vector protected synchronized void removerange (int fromindex, int toindex) {
        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; The Write function of//java.io.Serializable private synchronized void WriteObject (Java.io.ObjectOutputStream s) t
    Hrows java.io.IOException {s.defaultwriteobject (); }
}

Summarize:
Vector actually holds data in an array. When we construct VECOTR, if the default constructor is used, the default capacity size of the vector is 10.
(02) When the vector capacity is insufficient to accommodate all elements, the capacity of the vector increases. If the capacity increase coefficient is >0, increase the capacity value by "capacity increase factor", otherwise, increase the capacity size by one times.
Vector's clone function, which is to clone all elements into an array.

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.