Java Source Code Analysis: Vector

Source: Internet
Author: User

Java Source Code Analysis: Vector

Although, vector collection in our programming, use less, at least I use less, in general, I tend to use the list to store some of the same type of elements.

In fact, the internal implementation of the vector and the internal implementation of the ArrayList are basically consistent, the internal is through the use of arrays to achieve. Let's analyze the following together.

HashMap type of source analysis, blog here: http://blog.csdn.net/u010412719/article/details/51980632

Hashtable type of source analysis, blog here: http://blog.csdn.net/u010412719/article/details/51972602

Linkedhashmap type of source analysis, blog here: http://blog.csdn.net/u010412719/article/details/51984455

1. Vector Inheritance Structure
    publicclass Vector<E>        extends AbstractList<E>        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

As can be seen from the inheritance structure, vector inherits the Abstractlist abstract class and implements the list, randomaccess, cloneable, serializable interface, and the structure vector of ArrayList.

The Randomaccess interface is commented on in the source code as follows: Marker interface used by the List implementations to indicate that
They support fast (generally constant time) random access. Translation is: This is a labeled interface, who implements this interface to show that he has the ability to quickly random access.

2. Vector Properties

Elementdata: An array that is used to store elements of

Elementcount: Record the number of data that has been saved in the array

Capacityincrement: The size of auto-expansion, that is, when the array is full, add capacityincrement space to load elements, if capacityincrement<=0, then expand to the current vector capacity of twice times

    protected Object[] elementData;    protectedint elementCount;    protectedint capacityIncrement;
3. Vector structure function
    /* Other constructors are instructions for calling this constructor parameter initialcapacity: Specifies the initial capacity, the default value is capacityincrement: Specifies the size of the expansion each time, the default value is 0, capacityincrement=0 means that, when the number of assemblies is full, the expansion is twice times the current array size * /     Public Vector(intInitialcapacity,intCapacityincrement) {Super();if(Initialcapacity <0)Throw NewIllegalArgumentException ("Illegal capacity:"+ initialcapacity); This. Elementdata =NewObject[initialcapacity]; This. capacityincrement = capacityincrement; } Public Vector(intinitialcapacity) { This(Initialcapacity,0); } Public Vector() { This(Ten); }

When we use vectors, if we know the approximate number of elements the vector stores, we specify the capacity of the vector and do not use the vector v= new vector () to create the vector instance object when the amount of storage is large. This is actually creating an object array with a length of 10 and a growth factor of 0. When the number of stores is large, the cost of copying the elements from the original array to the new array after the expansion is added.

The vector class also has the following constructor for initializing a vector object instance with collection

Internally implemented, the collection is converted directly to an array return.

    public Vector(Collection<? extends E> c) {        elementData = c.toArray();        elementCount = elementData.length;        // c.toArray6260652)        if (elementData.getClass() != Object[].class)            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);    }
Add (E) method

The method of adding an element is simple: add it directly to the next position in the array, but before adding the element, you need to check whether the array is full, and if it is full, expand it.

    publicsynchronizedbooleanadd(E e) {        modCount++;        1);        elementData[elementCount++] = e;        returntrue;    }

Expansion is unavoidable in vectors, so it is necessary to understand the next Ensurecapacityhelper function

Ensurecapacityhelper

This function is to check if the array is full and if it is full, call the Grow function to expand. After the expansion, the data can be copied.

Among them, in the Grow function if the data after the expansion of some judgment, for example, whether the detection overflow ah, the detection has reached the max_array_size ah, respectively, these have been some treatment.

The idea is relatively simple, so the source code is easier to read.

The expansion of the ArrayList class is identical to this.

The source code is as follows: (added some comments)

    Private void Ensurecapacityhelper(intmincapacity) {//Overflow-conscious code        //When the array is full, call the Grow function to expand the arrays        if(Mincapacity-elementdata.length >0) grow (mincapacity); }Private Static Final intMax_array_size = Integer.max_value-8;Private void Grow(intmincapacity) {//Overflow-conscious code        intoldcapacity = Elementdata.length;//The size of the expansion is determined by capacityincrement, and if capacityincrement<=0, it expands to twice times the current array        intNewcapacity = oldcapacity + (Capacityincrement >0) ? capacityincrement:oldcapacity);//Check if the newcapacity overflow        if(Newcapacity-mincapacity <0) newcapacity = mincapacity;if(Newcapacity-max_array_size >0) newcapacity = hugecapacity (mincapacity);//copy of the elementElementdata = arrays.copyof (Elementdata, newcapacity); }Private Static int hugecapacity(intmincapacity) {if(Mincapacity <0)//Overflow            Throw NewOutOfMemoryError ();return(Mincapacity > Max_array_size)?    Integer.MAX_VALUE:MAX_ARRAY_SIZE; }
Add (int index, E Element)

Functions: Adding elements at a specified location

The idea of the method implementation is also relatively simple: first check whether the need for expansion, if necessary, to expand; then move the array back one bit backwards from the index element. Finally, the element is saved at the index position of the array.

The source code is as follows: (added a little comment)

    //Add element at specified location     Public voidAddint Index, E Element) {Insertelementat (element,Index); } PublicSynchronizedvoidInsertelementat (E obj,int Index) {modcount++;//Validity check        if(Index> Elementcount) {Throw NewArrayIndexOutOfBoundsException (Index+">"+ Elementcount); }//Check if you need to expand, and if necessary, capacityEnsurecapacityhelper (Elementcount +1);//CopySystem.arraycopy (Elementdata,Index, Elementdata,Index+1, Elementcount-Index); elementdata[Index] = obj;    elementcount++; }
Get (int index) method

The two key methods for containers are: add elements, remove elements. Therefore, it is inevitable that we need to analyze the implementation of the Get method.

The Get method is simpler because the vector is implemented using arrays, so the internal implementation of the Get method is the element that takes the position index.

    public synchronized E get(intindex) {        if (index >= elementCount)            thrownew ArrayIndexOutOfBoundsException(index);        return elementData(index);    }

The Get and add methods above are decorated with the Synchronized keyword, which shows that they are thread-safe and do not require additional synchronization when multithreading is concurrent. The ArrayList is not synchronized. This is also a difference between vector and ArrayList.

Set (int index, E Element) method

Since we know that the bottom of the vector is based on an array, then the set method we want to use the buttocks are how to achieve, relatively simple ha.

    public synchronized E set(intindex, E element) {        if (index >= elementCount)            thrownew ArrayIndexOutOfBoundsException(index);        E oldValue = elementData(index);        elementData[index] = element;        return oldValue;    }
Remove (Object o) method

Function: Remove the element O.

Idea: Find the position of the element in the array index first, and then remove the element at index position

After the idea is clear, the source code will be better understood.

The source code is as follows: (added some comments)

    /* Function: remove element O. Idea: First find the position of the element in the array index, and then remove the element indexed at index position * /     Public Boolean Remove(Object o) {returnRemoveelement (o); } Public synchronized Boolean removeelement(Object obj) {modcount++;inti = indexOf (obj);if(I >=0) {Removeelementat (i);return true; }return false; } Public int indexOf(Object o) {returnIndexOf (O,0); }/* Function: Find the position of element o where the array appears after the index position */     Public synchronized int indexOf(Object O,intIndex) {if(O = =NULL) { for(inti = index; i < Elementcount; i++)if(elementdata[i]==NULL)returnI }Else{ for(inti = index; i < Elementcount; i++)if(O.equals (Elementdata[i]))returnI }return-1; } Public synchronized void Removeelementat(intindex) {modcount++;if(Index >= Elementcount) {Throw NewArrayIndexOutOfBoundsException (Index +">="+ Elementcount); }Else if(Index <0) {Throw NewArrayIndexOutOfBoundsException (index); }intj = Elementcount-index-1;if(J >0) {system.arraycopy (elementdata, index +1, Elementdata, index, J);        } elementcount--; Elementdata[elementcount] =NULL;/* To-let GC do it work * /}

The above removes the element, and the vector also provides a different form of remove,

Remove (int index)

function function: Remove the vector index as the element of the position of index.

The realization of this source code is also relatively simple, the source code is as follows:

     PublicSynchronized E Remove (int Index) {modcount++;if(Index>= Elementcount)Throw NewArrayIndexOutOfBoundsException (Index); E OldValue = Elementdata (Index);intnummoved = Elementcount-Index-1;if(Nummoved >0) System.arraycopy (Elementdata,Index+1, Elementdata,Index, nummoved); Elementdata[--elementcount] =NULL;/Let GC do it work        returnOldValue; }
Elements method

An enumeration type is created in the method, in which the implementation or the element is present, and the array is traversed by the subscript, which is described too much here.

     PublicEnumeration<e>Elements() {return NewEnumeration<e> () {intCount =0; Public Boolean hasmoreelements() {returnCount < Elementcount; } PublicEnextelement() {synchronized(Vector. This) {if(Count < Elementcount) {returnElementdata (count++); }                }Throw NewNosuchelementexception ("Vector Enumeration");    }        }; }
Summary

There are many methods in vector, we just need to know that the vector is based on the array to achieve, and then use normal thinking to think about the implementation of common methods there is no problem, here do not do too much introduction. Note that vector is thread-safe, so there is no need for extra synchronization in multithreaded concurrency, and the ArrayList implementation is basically the same as a vector, but the difference is that ArrayList is thread insecure and requires additional synchronization when multithreading is concurrent

Java Source Code Analysis: Vector

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.