A vector introduction to the collection of Java Collection series--list (Iv.) __java Collection

Source: Internet
Author: User
Tags addall object object

1. Introduction to vector jdk1.7.0_79 version
The Vector class can implement an array of objects that can grow. Like an array, it contains components that can be accessed using an integer index. However, the size of the vector can grow or shrink as needed to accommodate the addition or removal of an item after the vector is created. Vectors are synchronized and can be used for multithreading.

public class vector<e>
    extends abstractlist<e>
    implements List<e>, Randomaccess, cloneable , java.io.Serializable

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.

Vector implements the Serializable interface and supports serialization.

the inheritance relationship of 2.Vector

Vector API

Java.lang.Object successor
  Java.util.abstractcollection<e> successor
      java.util.abstractlist<e> successor
          Java.util.vector<e>
All implemented interfaces:
Serializable, cloneable, Iterable<e>, Collection<e>, List <e>, randomaccess
directly known subclass:
Stack

API for 3.Vector
Note that the method is synchronized modified to achieve synchronization.

Synchronized Boolean Add (E object) void Add (int location, E object) Synchronized Boolean AddAll (collection< extends e> Collection) synchronized boolean addall (int location, collection<? exte
             NDS e> Collection) synchronized void AddElement (E object) synchronized int capacity () void clear () Synchronized Object Clone () Boolean contains (object) Synchroniz Ed Boolean containsall (collection<?> Collection) synchronized void Copyinto (object[) elements) sync hronized e elementat (int location) enumeration<e> elements () synchronized void E nsurecapacity (int minimumcapacity) Synchronized Boolean equals (object) synchronized E Firstelem ENT () E get (int location) synchronized int hashcode () synchronized int ind Exof (Object object, intLocation) int IndexOf (object) synchronized void Insertelementat (E object, int loc ation) Synchronized Boolean isempty () synchronized E lastelement () synchronized int lastind Exof (Object object, int location) synchronized int LastIndexOf (object) synchronized E Remov E (int location) Boolean remove (Object object) Synchronized Boolean RemoveAll (Collection<?&gt ; 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 ()

4.Vector Source Analysis

public class Vector<e> extends abstractlist<e> implements List<e>, Randomaccess, Cloneable, Java . Io.
     Serializable {/** * The array buffer for the storage vector component.

    * * protected object[] elementdata;
     Number of valid components in the/** * Vector object.

    * * protected int elementcount;
     /** * The amount of capacity automatically increases when the size of the vector is greater than its capacity.

    * That is, the capacity growth factor * @serial * * protected int capacityincrement; /** use Serialversionuid from JDK 1.0.2 for interoperability * * Private static final long Serialversionuid =-27676056

    14048989439L;
     /** * Constructs a empty vector with the specified initial capacity and * capacity increment.
     * * Constructs an empty vector using the specified initial capacity and capacity increment.
        * Specifies the vector "capacity size" and "growth factor" constructors/* public Vector (int initialcapacity, int capacityincrement) {super ();
                                               if (initialcapacity < 0) throw new illegalargumentexception ("illegal Capacity:" +
        initialcapacity); ThIs.elementdata = new Object[initialcapacity];
    This.capacityincrement = capacityincrement; }/** * Constructs a empty vector with the specified initial capacity and *, and its capacity, EQ
     UAL to zero.

     * * Constructs an empty vector using the specified initial capacity and the capacity increment equal to zero.
    * * Public Vector (int initialcapacity) {This (initialcapacity, 0); /** * Constructs a empty vector so it internal data array * has size {@code} and its standard C
     Apacity Increment is * zero.
     * Construct an empty vector so that its internal data array size is 10, and its standard capacity increment is zero.
    * * Public Vector () {this (10); /** * Constructs a vector containing the elements of the specified * collection, in the order they are re
     Turned by the collection ' s * iterator.
     * Construct a vector that contains the elements in the specified collection, * These elements are arranged in the order in which they return the elements in their collection iterator.
        * */Public Vector (COLLECTION&LT; extends e> c) {elementdata = C.toarray (); Elementcount = ELEMENTDATa.length;
            C.toarray might (incorrectly) not return object[] (= 6260652) if (Elementdata.getclass ()!= object[].class)
    Elementdata = arrays.copyof (Elementdata, Elementcount, Object[].class);
     }/** * Copies the components of this vector into the specified array.
     * The item at index {@code k} in this vector is copied into * component {@code k} of {@code Anarray}. * Copies the component of this vector into the specified array.
     The items in the index k in this vector are copied to the Anarray component K. * Copy all elements of the array vector to the array anarray/public synchronized void Copyinto (object[) anarray) {System.arraycop
    Y (elementdata, 0, Anarray, 0, Elementcount);  
     /** * Sets the current capacity value to = number of actual elements * to fine-tune the capacity of this vector so that it equals the current size of the vector. * * Public synchronized void TrimToSize () {modcount++//vector change statistics +1 int oldcapacity = Elementdata
        . length;
        if (Elementcount < oldcapacity) {Elementdata = arrays.copyof (Elementdata, Elementcount);
 }
    }

    /**    * Increase the capacity of this vector (if necessary) to ensure that it can hold at least the number of components specified by the minimum capacity parameter. * * @param mincapacity the desired minimum capacity * mincapacity required minimum capacity/public sy
            nchronized void ensurecapacity (int mincapacity) {if (mincapacity > 0) {modcount++;
     Ensurecapacityhelper (mincapacity)//confirm the "vector capacity" help function}/** * This implements the ensurecapacity semantics of the different steps.
     * The synchronization method in this class can call this method internally to ensure capacity without causing additional synchronization costs. * */private void ensurecapacityhelper (int mincapacity) {//Overflow-conscious code if (Mincapac
    Ity-elementdata.length > 0) grow (mincapacity);

    /** * Maximum-8, to prevent outofmemoryerror * * private static final int max_array_size = integer.max_value-8;
    Whether the vector capacity increases.
        private void Grow (int mincapacity) {//overflow-conscious code int oldcapacity = elementdata.length;
                     int newcapacity = oldcapacity + (capacityincrement > 0)?                    capacityincrement:oldcapacity);
        if (newcapacity-mincapacity < 0) newcapacity = mincapacity;
        if (newcapacity-max_array_size > 0) newcapacity = hugecapacity (mincapacity);
    Elementdata = arrays.copyof (Elementdata, newcapacity); //hugecapacity large capacity maximum capacity integer.max_value private static int hugecapacity (int mincapacity) {if (mincap
        Acity < 0)//overflow throw new OutOfMemoryError ();
            Return (Mincapacity > Max_array_size)?
    Integer.MAX_VALUE:MAX_ARRAY_SIZE; }/** * Sets the size of this vector.  If the new size is greater than the * current size, new {@code null} items are added to the "end of *" vector.
     If The new size is less than the current size, all * Components at index {@code newsize} and greater are. * Set the size of this vector.
     If the new size is greater than the current size, a corresponding number of NULL entries are added at the end of the vector. * If the new size is less than the current size, discard all items in and after the index newsize.
     * @param newsize The new size of this vector * @throws arrayindexoutofboundsexception If the new size is neg
        ative negative, throw an exception/public synchronized void setSize (int newsize) {modcount++;
        if (NewSize > Elementcount) {ensurecapacityhelper (newsize);
            else {for (int i = newsize i < Elementcount; i++) {elementdata[i] = null;
    } elementcount = newsize; /** * Returns the current capacity of this vector. 
     If the newly initialized * vector<string> v = new vector<string> (); 
    * V.capacity returns to v.size 0/public synchronized int capacity () {return elementdata.length;
     }/** * Returns the number of components in this vector. * Returns the number of components in this vector.
     The element size of the array in the vector. * @return The number of components in this vector/public synchronized int size () {return Elementcoun
    T }/** * Tests If this vector has no componeNts.
     * Test whether this vector does not contain a component (Element) * Returns True if and only if the vector does not have a component (that is, its size is 0);
    * * Public synchronized Boolean IsEmpty () {return elementcount = 0; /** * Returns an enumeration of the components of this vector.
     The returned enumeration object will generate all the items in this vector.
     * The first item generated is the item at index 0, then the item at index 1, and so on. * (1) * for (enumeration<string> elements = v.elements (); elements.hasmoreelements ();) * SYSTEM.OUT.PRINTF (
     Elements.nextelement ());    
     * (2) * while (elements.hasmoreelements ()) * SYSTEM.OUT.PRINTF (Elements.nextelement ());

            */Public enumeration<e> elements () {return new enumeration<e> () {int count = 0;
            public boolean hasmoreelements () {return count < Elementcount; Public E nextelement () {synchronized (vector.this) {if (Count < El
                    Ementcount) {return elementdata (count++);
      }
                }          throw new Nosuchelementexception ("Vector enumeration");
    }
        };
     /** * Returns True if this vector contains the specified element.
     * To be more precise, * returns true if and only if this vector contains at least one element E (o==null e==null:o.equals (e)).
    * */public Boolean contains (Object o) {return indexOf (o, 0) >= 0;
     /** * Returns the index of the specified element that appears for the first time in this vector, or 1 if the vector does not contain the element.
     * Rather, return a minimum index of o==null (i) ==null:o.equals (get (i)) (i) if there is no such index, return-1.
    */public int indexOf (Object o) {return indexOf (o, 0); /** * Returns the index of the specified element that appears for the first time in this vector, forward search from index, * If the element is not found, return-1. More specifically, * Returns the minimum index for satisfying (I >= index && (i) ==null:o.equals (get (i))) i; * If there is no such index, return-1
     。
            */Public synchronized int indexOf (Object o, int index) {//null and NOT NULL if (o = = null) {
      for (int i = index; i < elementcount; i++)//forward search from index, default from 0 to start if (elementdata[i]==null)              return i;
                    else {for (int i = index; i < Elementcount i++) if (O.equals (elementdata[i))
        return i;
    } return-1;
     /** * Returns the index of the last occurrence of the specified element in this vector, or 1 if the vector does not contain the element.
     * More specifically, returns the highest index of the satisfied (o==null. Get (i) ==null:o.equals) (i) if there is no such index, return 1.
    * * Public synchronized int lastindexof (Object o) {return LastIndexOf (o, elementCount-1);
     /** * Returns the index of the last occurrence of the specified element in this vector, searches backwards from index, and returns 1 if the element is not found.
     * More specifically, return to satisfaction (i) <= index && (i) ==null:o.equals (get (i))) (i; * if there is no such index, return-1. */Public synchronized int LastIndexOf (Object o, int index) {if (index >= elementcount) thro

        W New Indexoutofboundsexception (index + ">=" + elementcount); if (o = = null) {for (int i = index; I >= 0; i--)//forward search from index, default from ElementCount-1 to start if ( ElementdaTa[i]==null) return i;
                    else {for (int i = index; I >= 0; i--) if (O.equals (elementdata[i))
        return i;
    } return-1;
     /** * Returns the component at the specified index. * This method features exactly the same functionality as the get (int) method (which is part of the List Interface)/public synchronized E elementat (int index) {if (Index &
        Gt;= Elementcount) {throw new ArrayIndexOutOfBoundsException (index + ">=" + elementcount);
     Return Elementdata (index);//Find element}/** * Returns the item at index 0 for the first component of this vector. */Public synchronized E firstelement () {if (Elementcount = 0) {throw new Nosuchelementexceptio
        N ();
    Return Elementdata (0);
     /** the last component of the * vector, which is the component at index size ()-1. */Public synchronized E lastelement () {if (Elementcount = 0) {throw new nosuchelementexception
        (); Return Elementdata (elementCount-1);
    /** * Sets this vector to specify the component at index to the specified object.
     Discards the previous component (element) of the location.
     * The index must be a value greater than or equal to 0 and less than the current size of the vector.  * * Public synchronized void Setelementat (E obj, int index) {if (index >= elementcount) {throw New ArrayIndexOutOfBoundsException (index + ">=" + elementcount)
        ;
    } Elementdata[index] = obj; /** * Deletes the component at the specified index. Each component in this vector that is greater than or equal to the specified index is moved down, making its index value 1 smaller than before.
     The size of this vector will be reduced by 1.
     * * Index must be a value greater than or equal to 0 and less than the current size of the vector.
        * * 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;
     * To-let GC does its work make it work on/}/** * Inserts the specified object as a component in this vector to the specified index. * Each component in this vector that is greater than or equal to the specified index will shift upward so that its index value becomes 1 greater than the previous value/public 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++;
     /** * Adds the specified component to the end of this vector, increasing its size by 1.
     * If the size of the vector is larger than the capacity, then increase its capacity.
        * * Public synchronized void addelement (E obj) {modcount++; Ensurecapacityhelper (Elementcount + 1),//interpretation capacity size, need to increase capacity Elementdata[elementcount++] = obj;
     Default Add}/** * Removes the first (index least) occurrence of a variable from this vector. * If the object is found in this vector, each component in the vector whose index is greater than or equal to the object's index is moved down, making its index value a value smaller than the previous 1/public synchronized Boolean removeelement (Ob
        Ject obj) {modcount++; int i = indexOf (obj);
        Query obj index position if (I >= 0) {removeelementat (i);//Remove the first occurrence of the variable return true;
    return false;
     /** * Removes all components from this vector and sets its size to zero.
        * * Public synchronized void removeallelements () {modcount++;  Let GC does its work for (int i = 0; i < Elementcount; i++) elementdata[i] = null;  All set to null Elementcount = 0; The Elementcount size is set to 0}/** * Returns a copy of the vector.
     The copy will contain a reference to a copy of the internal data array, and not a reference to the original internal data array for this Vector object. * * Public synchronized Object clone () {try {@SuppressWarnings ("unchecked") vecto
            R<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 NE
        W Internalerror ();
     }/** * Returns An array containing the elements in this Vector * in the correct order.
     * Returns an array containing all the elements in the vector that are stored in the proper order. 
    * @since 1.2 * * * public synchronized object[] ToArray () {return arrays.copyof (Elementdata, Elementcount);
     /** * Returns an array containing all the elements in the vector in the proper order; the Run-time type of the array returns the type of the specified array. */@SuppressWarnings ("unchecked") public synchronized <T> t[] ToArray (t[] a) {if a.length < ele

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

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

        if (A.length > Elementcount) a[elementcount] = null;
    return A; }//Positional AcCess Operations//positioning access Operation @SuppressWarnings ("unchecked") E elementdata (int index) {return (E) element
    Data[index];
     /** * Returns the element at the specified position in the vector. */Public synchronized E get (int index) {if (index >= elementcount) throw new ARRAYINDEXOUTOFB

        Oundsexception (index);
    Return Elementdata (index);
     /** * Replaces the element at the specified position in this vector with the specified element. * * Public synchronized E set (int index, E element) {if (index >= elementcount) throw new Array

        Indexoutofboundsexception (index);
        E OldValue = elementdata (index);
        Elementdata[index] = element;
    return oldValue;
     /** * Adds the specified element to the end of this vector.
        * * Public Synchronized Boolean add (E e) {modcount++;
        Ensurecapacityhelper (Elementcount + 1);
        elementdata[elementcount++] = e;
    return true;
     /** * Removes the first occurrence of the specified element in this vector, and if the vector does not contain the element, the element remains unchanged. * More specifically, remove its index i satisfaction (o==null? Get (i) ==null:o.eqThe element of uals (get (i)), if such an element exists.
    */Public Boolean remove (Object o) {return removeelement (o); /** * Inserts the specified element at the specified position in this vector.
     Moves the element currently at that position (if any) and all subsequent elements to the right (add its index to 1).
    */public void Add (int index, E element) {Insertelementat (element, index); /** * Removes the element at the specified position in this vector.
     Moves all subsequent elements to the left (the index is reduced by 1).
     * Returns the elements removed from this vector.
        * * Public synchronized E Remove (int index) {modcount++;
        if (index >= elementcount) throw new ArrayIndexOutOfBoundsException (index);

        E OldValue = elementdata (index);
        int nummoved = elementcount-index-1; if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, index, n
        ummoved); Elementdata[--elementcount] = null;
    Let GC does its work return oldValue; /** * Removes all elements from this vector.
     When this call returns, the vector will be empty (unless an exception is thrown). * Public Voi

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.