JAVA Vector Source resolution and sample code _java

Source: Internet
Author: User
Tags addall int size object object

Part 1th 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

The relationship between vector and collection is as follows:

The constructor of a vector

Copy Code code as follows:

Vector has a total of 4 constructors
Default constructor
Vector ()
The 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)
The capacity is the default capacity size of the vector, and capacityincrement is the increment for each vector capacity increase.
Vector (int capacity, int capacityincrement)
Create a vector that contains collection
Vector (collection< extends e> Collection)



Vector API


Copy Code code as follows:



Synchronized Boolean Add (E object)


void Add (int location, E object)


Synchronized Boolean addall (collection&lt;? extends e&gt; Collection)


Synchronized boolean addall (int location, collection&lt;? extends e&gt; Collection)


synchronized void AddElement (E object)


synchronized int Capacity ()


void Clear ()


Synchronized Object Clone ()


Boolean contains (Object object)


Synchronized Boolean containsall (collection&lt;?&gt; Collection)


synchronized void Copyinto (object[] elements)


Synchronized E elementat (int location)


Enumeration&lt;e&gt; elements ()


synchronized void ensurecapacity (int minimumcapacity)


Synchronized Boolean equals (Object object)


Synchronized E firstelement ()


E get (int location)


synchronized int hashcode ()


synchronized int IndexOf (object object, int location)


int IndexOf (Object object)


synchronized void Insertelementat (E object, int location)


Synchronized Boolean IsEmpty ()


Synchronized E lastelement ()


synchronized int LastIndexOf (object object, int location)


synchronized int LastIndexOf (Object object)


Synchronized E Remove (int location)


Boolean Remove (Object)


Synchronized Boolean removeall (collection&lt;?&gt; Collection)


synchronized void Removeallelements ()


Synchronized Boolean Removeelement (Object object)


synchronized void Removeelementat (int location)


Synchronized Boolean retainall (collection&lt;?&gt; 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&lt;e&gt; sublist (int start, int end)


Synchronized &lt;T&gt; t[] ToArray (t[] contents)


Synchronized object[] ToArray ()


Synchronized String toString ()


synchronized void TrimToSize ()








The 2nd part vector Source analysis
To get a better idea of vector, the following is an analysis of the vector source code.


Copy Code code as follows:



Package java.util;


public class Vector&lt;e&gt;


Extends abstractlist&lt;e&gt;


Implements List&lt;e&gt, Randomaccess, cloneable, java.io.Serializable


{





To save an array of data in a vector


protected object[] Elementdata;


Number of actual data


protected int elementcount;


Capacity growth factor


protected int capacityincrement;


The sequence version number of the vector


Private static final long serialversionuid = -2767605614048989439l;


The Vector constructor. The default capacity is 10.


Public Vector () {


This (10);


}


constructor that specifies the size of the vector capacity


Public Vector (int initialcapacity) {


This (initialcapacity, 0);


}


constructor that specifies the vector "capacity size" and "Growth factor"


Public Vector (int initialcapacity, int capacityincrement) {


Super ();


if (initialcapacity &lt; 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&gt; c) {


Gets an array of "set (c)" and assigns it to the Elementdata


Elementdata = C.toarray ();


Set the length of an array


Elementcount = Elementdata.length;


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


if (Elementdata.getclass ()!= object[].class)


Elementdata = arrays.copyof (Elementdata, Elementcount, Object[].class);


}


Copies all elements of an array vector into the array anarray


Public synchronized void Copyinto (object[] anarray) {


System.arraycopy (elementdata, 0, Anarray, 0, Elementcount);


}


Set current capacity value to = number of actual elements


Public synchronized void TrimToSize () {


modcount++;


int oldcapacity = Elementdata.length;


if (Elementcount &lt; oldcapacity) {


Elementdata = arrays.copyof (Elementdata, Elementcount);


}


}


To confirm the 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 &gt;0 (ie capacityincrement&gt;0), the capacity is increased when capacityincrement


Otherwise, the capacity is increased by one fold.


if (Mincapacity &gt; Oldcapacity) {


object[] OldData = elementdata;


int newcapacity = (capacityincrement &gt; 0)?


(Oldcapacity + capacityincrement): (oldcapacity * 2);


if (Newcapacity &lt; mincapacity) {


newcapacity = mincapacity;


}


Elementdata = arrays.copyof (Elementdata, newcapacity);


}


}


Determine the capacity of the vector.


Public synchronized void ensurecapacity (int mincapacity) {


Statistics of Vector Change +1


modcount++;


Ensurecapacityhelper (mincapacity);


}


Set capacity value to NewSize


Public synchronized void setSize (int newsize) {


modcount++;


if (NewSize &gt; 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 &lt; Elementcount; i++) {


Elementdata[i] = null;


}


}


Elementcount = newsize;


}


Returns "The total capacity of the vector"


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&lt;e&gt; elements () {


Implementing enumeration with Anonymous classes


return new enumeration&lt;e&gt; () {


int count = 0;


Whether the next element exists


public boolean hasmoreelements () {


return count &lt; Elementcount;


}


Get Next element


Public E nextelement () {


Synchronized (vector.this) {


if (Count &lt; 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) &gt;= 0;


}

Finds the element backward from the index position (o).


Returns the index value of the element if found; otherwise, returns-1


public synchronized int indexOf (Object o, int index) {


if (o = = null) {


If the lookup element is NULL, the null element is found and the corresponding ordinal is returned


for (int i = index; i &lt; elementcount; i++)


if (elementdata[i]==null)


return i;


} else {


If the lookup element is not NULL, the element is located and the corresponding ordinal is returned


for (int i = index; i &lt; elementcount; i++)


if (O.equals (Elementdata[i]))


return i;


}


return-1;


}


Finds and returns the index value of an element (O) in a vector


public int indexOf (Object o) {


Return indexOf (o, 0);


}


Looks up 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);


}


Looks up 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 index value of the element, otherwise, returns-1.


public synchronized int LastIndexOf (Object o, int index) {


if (index &gt;= elementcount)


throw new Indexoutofboundsexception (index + "&gt;=" + elementcount);


if (o = = null) {


If the lookup element is NULL, the null element is reversed and its corresponding ordinal is returned.


for (int i = index; I &gt;= 0; i--)


if (elementdata[i]==null)


return i;


} else {


If the lookup element is not NULL, the element is reversed and its corresponding ordinal is returned.


for (int i = index; I &gt;= 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 &gt;= elementcount) {


throw new ArrayIndexOutOfBoundsException (index + "&gt;=" + 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 of index position to obj


Public synchronized void Setelementat (E obj, int index) {


if (index &gt;= elementcount) {


throw new ArrayIndexOutOfBoundsException (index + "&gt;=" +


Elementcount);


}


Elementdata[index] = obj;


}


Delete element of index position


Public synchronized void Removeelementat (int index) {


modcount++;


if (index &gt;= elementcount) {


throw new ArrayIndexOutOfBoundsException (index + "&gt;=" +


Elementcount);


else if (Index &lt; 0) {


throw new ArrayIndexOutOfBoundsException (index);


}


int j = elementcount-index-1;


if (J &gt; 0) {


System.arraycopy (elementdata, index + 1, elementdata, index, J);


}


elementcount--;


Elementdata[elementcount] = null; * To let GC does its work * *


}


Inserts an element at the index position (obj)


Public synchronized void Insertelementat (E obj, int index) {


modcount++;


if (Index &gt; Elementcount) {


throw new ArrayIndexOutOfBoundsException (index


+ "&gt;" + elementcount);


}


Ensurecapacityhelper (Elementcount + 1);


System.arraycopy (Elementdata, index, Elementdata, index + 1, elementcount-index);


Elementdata[index] = obj;


elementcount++;


}


Add "element obj" to the end of a vector


Public synchronized void addelement (E obj) {


modcount++;


Ensurecapacityhelper (Elementcount + 1);


elementdata[elementcount++] = obj;


}


Finds and deletes 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 &gt;= 0) {


Removeelementat (i);


return true;


}


return false;


}


Delete all elements in a vector


Public synchronized void Removeallelements () {


modcount++;


To set all elements in a vector to null


for (int i = 0; i &lt; Elementcount; i++)


Elementdata[i] = null;


Elementcount = 0;


}


Cloning functions


Public synchronized Object Clone () {


try {


Vector&lt;e&gt; v = (vector&lt;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 new Internalerror ();


}


}


Return Object array


Public synchronized object[] ToArray () {


Return arrays.copyof (Elementdata, Elementcount);


}


Returns a template array of vectors. The so-called template array, that is, you can set the T to any data type


Public synchronized &lt;T&gt; t[] ToArray (t[] a) {


If the size of the array a &lt; vector number of elements;


A new t[] array is created, the array size is the number of elements of the vector, and the vector is copied to the new array


if (A.length &lt; Elementcount)


Return (t[]) arrays.copyof (Elementdata, Elementcount, A.getclass ());


If the size of the array a &gt;= the number of vector elements;


Copies all the elements of the vector to array a.


System.arraycopy (elementdata, 0, a, 0, elementcount);


if (A.length &gt; Elementcount)


A[elementcount] = null;


return A;


}


Gets the element of the index position


Public synchronized E get (int index) {


if (index &gt;= elementcount)


throw new ArrayIndexOutOfBoundsException (index);


Return (E) Elementdata[index];


}


The value of the index position is set to element. and return the original value of the index position


Public synchronized e Set (int index, e element) {


if (index &gt;= 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;


}


Delete element o in vector


public boolean remove (Object o) {


return Removeelement (o);


}


Adding element elements at the index position


public void Add (int index, E element) {


Insertelementat (element, 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 &gt;= elementcount)


throw new ArrayIndexOutOfBoundsException (index);


Object oldValue = Elementdata[index];


int nummoved = elementcount-index-1;


if (nummoved &gt; 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 ();


}


Returns whether a vector contains a collection C


Public synchronized Boolean containsall (collection&lt;?&gt; c) {


return Super.containsall (c);


}


Add collection C to the vector


Public synchronized Boolean addall (collection&lt;? extends e&gt; c) {


modcount++;


Object[] A = C.toarray ();


int numnew = A.length;


Ensurecapacityhelper (Elementcount + numnew);


Copies all elements of the set C into the array elementdata


System.arraycopy (A, 0, Elementdata, Elementcount, numnew);


Elementcount + = numnew;


return numnew!= 0;


}


Delete all elements of a collection C


Public synchronized Boolean RemoveAll (collection&lt;?&gt; c) {


return Super.removeall (c);


}


Delete elements in non-set C


Public synchronized Boolean retainall (collection&lt;?&gt; c) {


return Super.retainall (c);


}


Add collection C to the vector starting at the index position


Public synchronized Boolean addall (int index, COLLECTION&LT;? extends e&gt; c) {


modcount++;


if (Index &lt; 0 | | index &gt; ELEMENTCOUNT)


throw new ArrayIndexOutOfBoundsException (index);


Object[] A = C.toarray ();


int numnew = A.length;


Ensurecapacityhelper (Elementcount + numnew);


int nummoved = Elementcount-index;


if (nummoved &gt; 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);


}


Calculate hash value


public synchronized int Hashcode () {


return Super.hashcode ();


}


Call ToString of Parent class ()


Public synchronized String toString () {


return super.tostring ();


}


Gets the subset of Fromindex (including) to Toindex (not included) in the vector


Public synchronized list&lt;e&gt; sublist (int fromindex, int toindex) {


Return Collections.synchronizedlist (Super.sublist (Fromindex, Toindex), this);


}


Delete Fromindex to toindex elements in a 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;


}


Write function for java.io.Serializable


Private synchronized void WriteObject (Java.io.ObjectOutputStream s)


Throws 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 &gt;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.


The 3rd part vector traversal mode


Vector supports 4 kinds of traversal methods. It is recommended that you use the following second to traverse the vector because of the problem of efficiency.


Copy Code code as follows:

(01) The first kind, through the iterator traversal. That is, through the iterator to traverse.
Integer value = null;
int size = Vec.size ();
for (int i=0; i<size; i++) {
Value = (Integer) vec.get (i);
}
(02) The second, random access, through the index value to traverse.
Because vector implements the Randomaccess interface, it supports random access to elements via index values.
Integer value = null;
int size = Vec.size ();
for (int i=0; i<size; i++) {
Value = (Integer) vec.get (i);
}
(03) A third, another for loop. As follows:
Integer value = null;
for (Integer Integ:vec) {
value = Integ;
}
(04) The fourth kind, enumeration traversal. As follows:
Integer value = null;
Enumeration ENU = vec.elements ();
while (Enu.hasmoreelements ()) {
Value = (Integer) enu.nextelement ();
}



The code to test the efficiency of these traversal methods is as follows:


Copy Code code as follows:



Import java.util.*;


/*


* @desc the vector traversal method and the efficiency of the test program.


*


* @author Skywang


*/


public class Vectorrandomaccesstest {


public static void Main (string[] args) {


Vector vec= new vector ();


for (int i=0; i&lt;100000; i++)


Vec.add (i);


Iteratorthroughrandomaccess (VEC);


Iteratorthroughiterator (VEC);


IteratorThroughFor2 (VEC);


Iteratorthroughenumeration (VEC);





}


private static void israndomaccesssupported (List list) {


if (list instanceof randomaccess) {


System.out.println ("Randomaccess implemented!");


} else {


System.out.println ("Randomaccess not implemented!");


}


}


public static void Iteratorthroughrandomaccess (List list) {


Long StartTime;


Long Endtime;


StartTime = System.currenttimemillis ();


for (int i=0; i&lt;list.size (); i++) {


List.get (i);


}


Endtime = System.currenttimemillis ();


Long interval = Endtime-starttime;


System.out.println ("iteratorthroughrandomaccess:" + interval+ "MS");


}


public static void Iteratorthroughiterator (List list) {


Long StartTime;


Long Endtime;


StartTime = System.currenttimemillis ();


for (Iterator iter = List.iterator (); Iter.hasnext ();) {


Iter.next ();


}


Endtime = System.currenttimemillis ();


Long interval = Endtime-starttime;


System.out.println ("Iteratorthroughiterator:" + interval+ "MS");


}

public static void IteratorThroughFor2 (List list) {


Long StartTime;


Long Endtime;


StartTime = System.currenttimemillis ();


for (Object obj:list)





Endtime = System.currenttimemillis ();


Long interval = Endtime-starttime;


System.out.println ("IteratorThroughFor2:" + interval+ "MS");


}


public static void Iteratorthroughenumeration (Vector vec) {


Long StartTime;


Long Endtime;


StartTime = System.currenttimemillis ();


For (Enumeration ENU = vec.elements (); enu.hasmoreelements ();) {


Enu.nextelement ();


}


Endtime = System.currenttimemillis ();


Long interval = Endtime-starttime;


System.out.println ("iteratorthroughenumeration:" + interval+ "MS");


}


}





Run Result:


Iteratorthroughrandomaccess:6 ms


Iteratorthroughiterator:9 ms


Iteratorthroughfor2:8 ms


Iteratorthroughenumeration:7 ms


Summary: Traversing vectors, using random access to the index is the fastest, using the iterator slowest.


Part 4th Vector Example
The following example learns how to use the vector


Copy Code code as follows:



Import Java.util.Vector;


Import java.util.List;


Import Java.util.Iterator;


Import java.util.Enumeration;


/**


* @desc vector test function: Traversing vectors and common APIs


*


* @author Skywang


*/


public class Vectortest {


public static void Main (string[] args) {


New Vector


Vector vec = new vector ();





adding elements


Vec.add ("1");


Vec.add ("2");


Vec.add ("3");


Vec.add ("4");


Vec.add ("5");


Set the first element to 100


Vec.set (0, "100");


Insert "500" into position 3rd


Vec.add (2, "300");


System.out.println ("VEC:" +vec);


(Sequential lookup) Gets the index of 100


System.out.println ("Vec.indexof" (m): "+vec.indexof" ("100"));


(Reverse lookup) gets the index of 100


System.out.println ("Vec.lastindexof" (m): "+vec.lastindexof" ("100"));


Get first element


System.out.println ("Vec.firstelement ():" +vec.firstelement ());


Get 3rd Element


System.out.println ("Vec.elementat (2):" +vec.elementat (2));


Get the last element


System.out.println ("Vec.lastelement ():" +vec.lastelement ());


Get the size of a vector


SYSTEM.OUT.PRINTLN ("Size:" +vec.size ());


Gets the total capacity of the vector


SYSTEM.OUT.PRINTLN ("Capacity:" +vec.capacity ());


Gets the "2nd" to "4th" element of the vector


System.out.println ("Vec 2 to 4:" +vec.sublist (1, 4));


Traversing vectors through enumeration


Enumeration ENU = vec.elements ();


while (Enu.hasmoreelements ())


System.out.println ("Nextelement ():" +enu.nextelement ());





Vector Retainvec = new vector ();


Retainvec.add ("100");


Retainvec.add ("300");


Get a collection of elements contained in "Retainvec" in "VEC"


System.out.println ("Vec.retain ():" +vec.retainall (Retainvec));


System.out.println ("VEC:" +vec);





Gets the string array corresponding to the VEC


String[] arr = (string[]) Vec.toarray (new string[0));


for (String Str:arr)


System.out.println ("str:" +STR);


Empty the vector. Clear () and removeallelements ()!


Vec.clear ();


Vec.removeallelements ();


Determine if the vector is empty


System.out.println ("Vec.isempty ():" +vec.isempty ());


}


}


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.