Java Collection source code analysis (4) Vector & lt; E & gt;, javavector

Source: Internet
Author: User

Java Collection source code analysis (4) Vector <E>, javavector
Vector <E> Introduction

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

Vector is introduced in JDK1.0. 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.

Vector does not have the 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 <E> source code

As follows (Added detailed notes ):

/** @ (#) Vector. java1.106 06/06/16 ** Copyright 2006 Sun Microsystems, Inc. all rights reserved. * sun proprietary/CONFIDENTIAL. use is subject to license terms. */package java. util;/*** @ author Lee Boynton * @ author Jonathan Payne * @ version 1.106, 06/16/06 * @ see Collection * @ see List * @ see ArrayList * @ see collections List * @ since JDK1.0 */public class Vector <E> extends actlist <E> implements List <E>, RandomAccess, Cloneable, java. io. serializable {// Save the data array protected Object [] elementData; // the actual number of data protected int elementCount; // capacity growth factor protected int capacityIncrement; // Vector sequence version private static final long serialVersionUID =-2767605614048989439L; // The public Vector (int initialCapacity, int capacityIncrement) constructor that specifies the Vector "capacity" and "Growth Factor) {super (); if (initialCapacity <0) throw new Il LegalArgumentException ("Illegal Capacity:" + initialCapacity); this. elementData = new Object [initialCapacity]; this. capacityIncrement = capacityIncrement;} // The public Vector (int initialCapacity) {this (initialCapacity, 0);} // Vector constructor that specifies the Vector capacity. The default capacity is 10. Public Vector () {this (10) ;}// specify the Vector constructor of the set. 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 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 = Arrays. CopyOf (elementData, elementCount) ;}// determine the Vector capacity. Public synchronized void ensureCapacity (int minCapacity) {modCount ++; ensureCapacityHelper (minCapacity);} // confirm the "Vector capacity" Help function private void limit (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) ;}// set the capacity value to newSize public synchronized void setSize (int newSize) {modCount ++; if (newSize> elementCount) {// If "newSize is greater than Vector capacity", 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;} // determine whether the Vector is empty public synchronized boo Lean isEmpty () {return elementCount = 0;} // return "Enumeration" public Enumeration <E> elements () corresponding to all elements in the Vector () {// implement Enumerationreturn new Enumeration using an 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 ++] ;}} throw new NoSuchEle MentException ("Vector Enumeration") ;};}// returns whether the Vector contains the Object (o) public boolean contains (Object o) {return indexOf (o, 0)> = 0;} // search for and return the index value of the element (o) in the Vector public int indexOf (Object o) {return indexOf (o, 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) {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 and forth ). 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 position element of the Vector. // If the index exceeds the array size, 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 removeElem element at the index location EntAt (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; // notify gc collection} // Insert the element (obj) publi at the index position C synchronized void insertElementAt (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 the "element obj" to the end of the Vector public synchronized void addElement (E obj) {mo DCount ++; 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, notify gc to recycle 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 (); 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 new T [] array is created. 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;} // Positional Access Operations // gets the public synchronized E get (int index) element of the index position) {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 (I Ndex> = 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 workreturn (E) oldValue ;} // clear Vector public void clear () {removeAllElements ();} // Bulk Operations // returns the Vector Contains the set c public 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); elementCount + = 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 workint 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. I will not make a detailed analysis here. If you are interested, refer to the articles in 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 as 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.

 

 

--------------------------------------------------------------

References

[Java Collection source code analysis] Vector source code analysis

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.