Java Collection source code analysis (iv) vector<e>

Source: Internet
Author: User
Tags addall

vector<e> Introduction

Vector is also based on an array, and is a dynamic array whose capacity can be automatically increased.

Vector is JDK1.0 introduced, many of its implementation methods are added to the synchronization statement, it is thread-safe (in fact, it is relatively safe, and sometimes to join a synchronous statement to ensure thread security), can be used in a multithreaded environment.

Vector does not have the silk thread serializable interface, therefore it does not support the serialization, realizes the Cloneable interface, can be cloned, realizes the Randomaccess interface, supports the fast random access.

vector<e> Source

as follows (detailed comments added):

/* * @ (#) vector.java1.106 06/06/16 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN proprietary/confidential. Use are subject to license terms. */package java.util;/** * @author Lee Boynton * @author Jonathan Payne * @version 1.106, 06/16/06 * @see Collection * @s EE List * @see ArrayList * @see LinkedList * @since JDK1.0 */public class Vector<e> extends ABSTRACTLIST&LT;E&G    T    Implements List<e>, Randomaccess, cloneable, java.io.serializable{//Save data Array protected object[] elementdata;    The number of actual data protected int elementcount;    Capacity growth coefficient protected int capacityincrement;    Vector sequence version number private static final long serialversionuid = -2767605614048989439l;        constructor for specifying vector "capacity size" and "growth factor" public vector (int initialcapacity, int capacityincrement) {super ();                                               if (initialcapacity < 0) throw new IllegalArgumentException ("Illegal capacity:" + initialcapacity); this.elementData = new object[initialcapacity];this.capacityincrement = capacityincrement;    }//Specifies the vector capacity size of the constructor public vector (int initialcapacity) {This (initialcapacity, 0); }//Vector constructor.    The default capacity is 10.    Public Vector () {this (10);    }//Specifies the vector constructor for the collection. Public Vector (collection<? extends e> c) {elementdata = C.toarray (); elementcount = elementdata.length;//C.toarray Might (incorrectly) not return object[] (see 6260652) if (Elementdata.getclass ()! = object[].class) Elementdata = Arrays    . CopyOf (Elementdata, Elementcount, Object[].class);  }//Copy all elements of the array vector into 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 (el    Ementcount < oldcapacity) {Elementdata = arrays.copyof (Elementdata, elementcount);}    }//Determine the capacity of the vector. public synchronized void Ensurecapacity (int mincapacity) {modcount++;ensurecapacityhelper (mincapacity); }//Confirm the help function for "vector capacity" private void ensurecapacityhelper (int mincapacity) {int oldcapacity = elementdata.length;//when The capacity of the vector is insufficient to accommodate all current elements, increasing the size of the capacity. If the capacity increment factor >0 (that is, capacityincrement>0), the capacity increases as capacityincrement//otherwise, the capacity is increased by one-fold.    if (Mincapacity > Oldcapacity) {object[] olddata = elementdata; int newcapacity = (capacityincrement > 0)?        (Oldcapacity + capacityincrement): (oldcapacity * 2);    if (Newcapacity < mincapacity) {newcapacity = mincapacity;    } Elementdata = arrays.copyof (Elementdata, newcapacity);} }//Set the capacity value to newSize public synchronized void setSize (int newSize) {modcount++;if (NewSize > Elementcount) {//if "n    Ewsize is larger than the vector capacity, the vector size is adjusted. Ensurecapacityhelper (newSize);} else {//if "newSize is less than/equal to vector capacity", the element starting with the NewSize position is set to NULL for (int i = newSize; i < Elementcount; i++) {ELEMENTDA    Ta[i] = null;    }}elementcount = newSize; }//returns "Vector'sTotal capacity "public synchronized int capacity () {return elementdata.length;    }//returns "The actual size of the vector", that is, the number of elements in the vector public synchronized int size () {return elementcount;    }//Determine if the vector is empty public synchronized Boolean isEmpty () {return elementcount = = 0; }//Returns "enumeration for all elements in vector" public enumeration<e> elements () {//Enumerationreturn new Enume via anonymous class    Ration<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) element    Data[count++];    }}throw new Nosuchelementexception ("Vector enumeration");    }};    }//Returns whether the vector contains object (o) Public boolean contains (object o) {return indexOf (o, 0) >= 0;    }//Finds and returns the index value of the element (o) in the vector public int indexOf (Object o) {return indexOf (o, 0);    }//Find the Element (O) backwards from the index position. Returns the index value of the element if it is found; otherwise, 1 public synchronized int indexOf (Object o, int index) {if (o = = null) {for (int i = index; i < elementcount; i++) if (elementdata[i]==null) return i;} else {for (int i = index; i < elementcount; i++) if (O.equals (Elementdata[i])) return i;}    return-1; }//Search for Elements (O) from the back forward.    and returns the index of the element public synchronized int lastIndexOf (Object o) {return lastIndexOf (o, elementCount-1); }//Search for Elements (O) from the back forward.    The starting position is the index number of the front and back, and//if found, returns the "indexed value" of the element; otherwise, 1. public synchronized int lastIndexOf (Object o, int index) {if (index >= elementcount) throw new index OutOfBoundsException (index + ">=" + elementcount); if (o = = null) {//If the lookup element is NULL, the null element is reversed 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, the element is reversed and returns 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 index exceeds the array size, the exception is thrown public synchronized E elementat (int index) {if (Index >= elemenTCount) {throw new ArrayIndexOutOfBoundsException (index + ">=" + Elementcount);}    Return (E) Elementdata[index];    }//Gets the first element in a vector.    If it fails, it throws 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, it throws an exception! Public synchronized E lastelement () {if (Elementcount = = 0) {throw new nosuchelementexception ();    Return (E) elementdata[elementcount-1]; }//Set the element value of index position to obj public synchronized void Setelementat (E obj, int index) {if (index >= elementcount) {T Hrow New ArrayIndexOutOfBoundsException (index + ">=" + elementcount);    Elementdata[index] = obj;    }//delete element at index position public synchronized void Removeelementat (int index) {modcount++;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;//notification GC Recycle}//Insert element at index position (obj) public synchronized void insert     ElementAt (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 end of the vector public synchronized void addelement (E obj) {modcount++;ensurecapacityhelper (Elementcount +    1); elementdata[elementcount++] = obj;    }//Find and delete the element obj in the 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; }//delete all elements in vector public synchronized voidRemoveallelements () {modcount++;//sets all elements in the vector to NULL, notifies the GC to recycle for (int i = 0; i < Elementcount; i++) elementd    Ata[i] = Null;elementcount = 0;    }//Clone function public synchronized Object clone () {try {vector<e> v = (vector<e>) super.clone ();    V.elementdata = arrays.copyof (Elementdata, Elementcount);    V.modcount = 0; return v;}     catch (Clonenotsupportedexception e) {//This shouldn ' t happen, since we is cloneable throw new Internalerror ();}     }//Returns an Object array public synchronized object[] ToArray () {return arrays.copyof (Elementdata, Elementcount); }//Returns a template array of vectors. The so-called template array, which can set T to any data type public synchronized <T> t[] ToArray (t[] a) {///If the size of array a < The number of elements of the vector, a new t[] array, array size Is "the number of elements of the vector" and copies all "vectors" to the new array if (A.length < Elementcount) return (t[]) arrays.copyof (elementdat        A, Elementcount, A.getclass ()); If the size of array a >= the number of elements in the vector, copy all the elements of the vector into array a. System.arraycopy (elementdata, 0, A, 0, elementcount);        if (A.length > Elementcount) a[elementcount] = null;    return A; }//positional access Operations//Gets the element of the index position public synchronized E get (int index) {if (Index >= Elementco    UNT) throw new ArrayIndexOutOfBoundsException (index); return (E) Elementdata[index]; }//sets the value of the 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 Arrayindexou    Tofboundsexception (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 elements in vector o public boolean remove (Object o) {return removeelement (o);    }//Add element at index position elements public void Add (int index, E element) {Insertelementat (element, index); }//delete the element at index position and return the inThe original value of the Dex position public synchronized E Remove (int index) {modcount++;if (index >= elementcount) throw new Arrayindexouto    Fboundsexception (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 Workreturn (E) OldValue;    }//empty vector public void clear () {removeallelements (); }//Bulk Operations//Returns whether the vector contains the collection C public synchronized Boolean containsall (collection<?> c) {R    Eturn Super.containsall (c);        }//Add the 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);//Copy all elements of the collection C into the array Elementdata system.arraycopy (A,        0, Elementdata, Elementcount, numnew);    Elementcount + = Numnew;return numnew! = 0; }//Delete collectionAll elements of C public synchronized Boolean RemoveAll (collection<?> c) {return super.removeall (c);    }//delete "elements in non-collection C" Public synchronized Boolean Retainall (collection<?> c) {return super.retainall (c); }//Starting from the index position, add the collection C to the vector public synchronized boolean addall (int index, COLLECTION&LT;? extends e> c) {mo        Dcount++;if (Index < 0 | | index > Elementcount) throw new ArrayIndexOutOfBoundsException (index); Object[] A = C.toarray (), int numnew = A.length;ensurecapacityhelper (Elementcount + numnew); int nummoved = Elementcount-i        Ndex;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 ();    }Invokes 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), t    His); }//Remove elements from vector fromIndex to toindex protected synchronized void removerange (int fromIndex, int toindex) {Modcount++;i        NT nummoved = Elementcount-toindex; System.arraycopy (Elementdata, Toindex, Elementdata, FromIndex, nummoved);/Let GC does its workint Newelementcount = Elementcount-(toindex-fromindex); while (elementcount! = newelementcount) Elementdata[--elementcoun    T] = null; }//Java.io.Serializable write function private synchronized void WriteObject (Java.io.ObjectOutputStream s) throws Jav    a.io.ioexception {s.defaultwriteobject (); }}
Brief summary

  Vector source of the implementation of the general and ArrayList similar, I do not make detailed analysis here, interested can be compared with my previous ArrayList article to see, about the source of vector, give the following summary:

  The 1.Vector has four different construction methods. The capacity of the non-parametric construction method is the default value of 10, and only the capacity of the construction method will increase the capacity (from the source can see the role of capacity growth, the 2nd will be the capacity growth of the detailed said) 0.

2. Pay attention to the method of expanding capacity ensurecapacityhelper. as with ArrayList, vectors call this method to ensure sufficient capacity each time an element is added (perhaps 1 or a group). When the capacity is not enough to accommodate the current number of elements, first look at the structure of the incoming capacity growth parameter capacityincrement is 0, if not 0, set a new capacity for capacity plus capacity growth, if 0, set a new capacity of twice times the old capacity, If the new capacity after Setup is not enough, the direct new capacity is set to the incoming parameter (that is, the required capacity), and the element is then 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 of the value of the element is divided into null and NOT null two case processing, the vector also allows the element is null.

5. Many other places are similar to the ArrayList, and vectors are now largely unused.

——————————————————————————————————————————————————————————————

Resources

"Java Collection source analysis" vector source analysis

Java Collection source code analysis (iv) vector<e>

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.