[Java Collection source code analysis] Vector source code analysis

Source: Internet
Author: User
Tags addall

Reprinted please indicate the source: http://blog.csdn.net/ns_code/article/details/35793865


Introduction to Vector

Vector is also implemented based on arrays. It is a dynamic array with its capacity Automatically increasing.

Javaslist is introduced in JDK. Many of its implementation methods are added with synchronous statements, so it is thread-safe (in fact, it is only relatively secure, in some cases, you still need to add synchronization statements to ensure thread security), which can be used in multi-threaded environments.

The serialize list does not have a silk line Serializable interface, so it does not support serialization. It implements the Cloneable interface, can be cloned, implements the RandomAccess interface, and supports fast and random access.


Vector source code analysis

The source code of Vector is as follows (detailed comments are added ):

Package java. util; public class Vector <E> extends actlist <E> implements List <E>, RandomAccess, Cloneable, java. io. serializable {// The array that stores the data in the Vector protected Object [] elementData; // the actual number of data protected int elementCount; // The capacity growth factor protected int capacityIncrement; // Vector sequence version: private static final long serialVersionUID =-2767605614048989439L; // Vector constructor. The default capacity is 10. Public Vector () {this (10) ;}// constructor that specifies the Vector capacity. public Vector (int initialCapacity) {this (initialCapacity, 0 );} // public Vector (int initialCapacity, int capacityIncrement) {super (); if (initialCapacity <0) throw new IllegalArgumentException ("Illegal Capacity:" + initialCapacity); // create an array with the array Capacity initialCapacity this. elementData = new Object [initialCapacity]; // sets the capacity. This. capacityIncrement = capacityIncrement;} // specify the Vector constructor of the set. Public Vector (Collection <? Extends E> c) {// obtain the array of "set (c)" and assign it to elementData = c. toArray (); // set the array length 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 to the array anArray public synchronized void copyInto (Object [] anArray) {System. arraycopy (elementData, 0, anArray, 0, elementCount);} // set the current capacity value to = actual number of elements public synchronized void trimToSize () {modCount ++; int oldCapacity = elementData. length; if (elementCount <oldCapacity) {elementData = Arr Ays. copyOf (elementData, elementCount) ;}// confirms the help function private void ensureCapacityHelper (int minCapacity) {int oldCapacity = elementData. length; // when the Vector capacity is insufficient to accommodate all the current elements, increase the capacity. // If the capacity increment coefficient is greater than 0 (capacityIncrement> 0), the capacity will be increased when capacityIncrement // otherwise, the capacity will be doubled. 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 Vector capacity. Public synchronized void ensureCapacity (int minCapacity) {// returns the number of Vector changes + 1 modCount ++; ensureCapacityHelper (minCapacity );} // set the capacity value to newSize public synchronized void setSize (int newSize) {modCount ++; if (newSize> elementCount) {// if "newSize is greater than Vector capacity ", then adjust the Vector size. EnsureCapacityHelper (newSize);} else {// If "newSize is less than/equal to Vector capacity", set all elements starting from the newSize position to null for (int I = newSize; I <elementCount; I ++) {elementData [I] = null ;}} elementCount = newSize ;}// return "Total Vector capacity" public synchronized int capacity () {return elementData. length ;}// return "actual Vector size", that is, the number of elements in the Vector public synchronized int size () {return elementCount;} // determines whether the Vector is empty public synchro Nized boolean isEmpty () {return elementCount = 0;} // returns "Enumeration" public Enumeration <E> elements () corresponding to all elements in a Vector () {// implement Enumeration return new Enumeration through the Anonymous class <E> () {int count = 0; // whether the next element public boolean hasMoreElements () {return count <elementCount ;} // obtain the next element public E nextElement () {synchronized (Vector. this) {if (count <elementCount) {return (E) elementData [count ++] ;}} thr Ow new NoSuchElementException ("Vector Enumeration") ;};}// returns whether the Vector contains the Object (o) public boolean contains (Object o) {return indexOf (o, 0)> = 0;} // search for elements (o) from the index position ). // If it is found, the index value of the element is returned; otherwise,-1 public synchronized int indexOf (Object o, int index) {if (o = null) is returned) {// if the search element is null, the system finds the null element forward and returns the corresponding sequence number for (int I = index; I <elementCount; I ++) if (elementData [I] = null) return I;} else {// if the search element is not null, it is positively located, return the corresponding sequence number for (int I = index; I <elementCount; I ++) if (o. equals (elementData [I]) return I;} return-1;} // search for and return the index value of the element (o) in the Vector public int indexO F (Object o) {return indexOf (o, 0) ;}// search for the element (o) from the back to the front ). And returns the index public synchronized int lastIndexOf (Object o) {return lastIndexOf (o, elementCount-1);} // looks forward from the back for the element (o ). The start position is the index number from the front to the back. // if it is found, the "index value" of the element is returned. Otherwise,-1 is returned. Public synchronized int lastIndexOf (Object o, int index) {if (index> = elementCount) throw new IndexOutOfBoundsException (index + "> =" + elementCount); if (o = null) {// if the search element is null, find the null element in the reverse direction and return its corresponding sequence number for (int I = index; I> = 0; I --) if (elementData [I] = null) return I;} else {// if the search element is not null, this element is found in the reverse direction, return the corresponding sequence number for (int I = index; I> = 0; I --) if (o. equals (elementData [I]) return I;} return -1;} // returns the index element in the Vector. // If the index is closed by month, an exception public synchronized E elementAt (int index) {if (index> = elementCount) is thrown) {throw new ArrayIndexOutOfBoundsException (index + "> =" + elementCount);} return (E) elementData [index];} // gets the first element in the Vector. // If it fails, an exception is thrown! Public synchronized E firstElement () {if (elementCount = 0) {throw new NoSuchElementException ();} return (E) elementData [0];} // obtain the last element in the Vector. // If it fails, an exception is thrown! Public synchronized E lastElement () {if (elementCount = 0) {throw new NoSuchElementException ();} return (E) elementData [elementCount-1];} // set the element value of the index position to obj public synchronized void setElementAt (E obj, int index) {if (index> = elementCount) {throw new ArrayIndexOutOfBoundsException (index + "> =" + elementCount);} elementData [index] = obj;} // Delete the public synchronized void remo element at the index location VeElementAt (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;/* to let gc do its wo Rk * // insert element (obj) public synchronized void insertElementAt (E obj, int index) {modCount ++; if (index> elementCount) at the index position) {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 publ Ic synchronized void addElement (E obj) {modCount ++; ensureCapacityHelper (elementCount + 1); elementData [elementCount ++] = obj ;} // search for and delete the element obj in the Vector. // If the call succeeds, true is returned. Otherwise, false is returned. Public synchronized boolean removeElement (Object obj) {modCount ++; int I = indexOf (obj); if (I> = 0) {removeElementAt (I); return true ;} return false;} // delete all elements in the 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>) super. clone (); // copy all elements of the current Vector to 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 the Object array public synchronized Object [] toArray () {return Arrays. copyOf (elementData, elementCount);} // returns the template array of the Vector. The so-called template array can set T to any data type public synchronized <T> T [] toArray (T []) {// if the size of array a is <number of elements of the Vector; // a T [] array is created, and the size of the array is "number of elements of the Vector ", and copy all "Vector" to the new array if (. length <elementCount) return (T []) Arrays. copyOf (elementData, elementCount,. getClass (); // if the size of array a is greater than or equal to the number of elements of the Vector; // all elements of the Vector are copied to array. System. arraycopy (elementData, 0, a, 0, elementCount); if (. length> elementCount) a [elementCount] = null; return a;} // obtain the index position element public synchronized E get (int index) {if (index> = elementCount) throw new ArrayIndexOutOfBoundsException (index); return (E) elementData [index];} // set the value of the index position to element. And return the original value 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 end of the Vector. Public synchronized boolean add (E e) {modCount ++; ensureCapacityHelper (elementCount + 1); elementData [elementCount ++] = e; return true ;} // Delete the element o public boolean remove (Object o) {return removeElement (o);} // add the element public void add (int index, E element) at the index position) {insertElementAt (element, index) ;}// Delete the element at the index position and return the original value 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 do its work return (E) oldValue ;} // clear Vector public void clear () {removeAllElements ();} // returns whether the Vector contains the set c p Ublic synchronized boolean containsAll (Collection <?> C) {return super. containsAll (c) ;}// add set c to public synchronized boolean addAll (Collection <? Extends E> c) {modCount ++; Object [] a = c. toArray (); int numNew =. length; ensureCapacityHelper (elementCount + numNew); // copy all elements of set c to the array elementData System. arraycopy (a, 0, elementData, elementCount, numNew); elementCount + = numNew; return numNew! = 0;} // delete all the public synchronized boolean removeAll (Collection <?> C) {return super. removeAll (c) ;}// Delete the public synchronized boolean retainAll (Collection <?> C) {return super. retainAll (c) ;}// add set c to public synchronized boolean addAll (int index, Collection <? Extends E> c) {modCount ++; if (index <0 | index> elementCount) throw new ArrayIndexOutOfBoundsException (index); Object [] a = c. toArray (); int numNew =. 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); elemen TCount + = numNew; return numNew! = 0;} // returns whether two objects are equal public synchronized boolean equals (Object o) {return super. equals (o) ;}// calculate the hash value public synchronized int hashCode () {return super. hashCode ();} // call the toString () public synchronized String toString () {return super. toString () ;}// obtain the public synchronized List from fromIndex (included) to toIndex (excluded) in the Vector <E> subList (int fromIndex, int toIndex) {return Collections. synchronizedList (supe R. subList (fromIndex, toIndex), this);} // Delete the element protected synchronized void removeRange (int fromIndex, int toIndex) {modCount ++; int numMoved = elementCount-toIndex; System. arraycopy (elementData, toIndex, elementData, fromIndex, numMoved); // Let gc do 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 ();}}
Summary

The source code implementation of Vector is similar to that of ArrayList. The source code of Vector is summarized as follows:

1. Vector has four different constructor methods. The capacity of the non-argument constructor is the default value of 10. The constructor that only contains the capacity will increase the capacity (from the source code, we can see the role of the capacity growth, the second point will also be detailed on the capacity growth) is set to 0.

2. ensureCapacityHelper. Like ArrayList, this method must be called every time a Vector adds an element (either one or a group) to ensure sufficient capacity. When the capacity is insufficient to accommodate the current number of elements, first check whether the capacity growth parameter CapacityIncrement passed in the constructor is 0. If the capacity is not 0, set the new capacity to the capacity plus the capacity growth. If the value is 0, set the new capacity to 2 times the old capacity. If the new capacity is not enough, the new capacity is directly set to the input parameter (that is, the required capacity), and then the Arrays is used. the copyof () method copies the elements to the new array.

3. synchronized synchronization statements are added to many methods to ensure thread security.

4. In the same way of searching for the index value of a given element, the source code processes the value of this element in two ways: null and not null. The element in the Vector is also allowed to be null.

5. The implementation of ArrayList is similar to that of ArrayList in many other places. Currently, Vector is basically no longer used.


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.