Click to view Java Collection framework Deep Understanding series,-(゜-゜) つロ Dry Cup ~
Today, the typhoon, hide in the house to see Vector.
It is said that Vector is a thread-safe ArrayList, today to look at the source to see if it is so similar. What is Vector
vectors, like ArrayList, inherit from Abstractlist. It is the parent class of the Stack. The meaning of English is "vector".
Vector member Variable
1. The bottom is also the number group
protected object[] Elementdata;
2. The number of elements of the array, why not call size it. Strange
protected int elementcount;
3. Increase the number of expansion, allowing users to set their own. If this value is 0 or negative, expansion will expand twice times, instead of 1.5
protected int capacityincrement;
4. Default capacity
private static final int default_size = 10;
4 Methods of Vector construction
Creates an array with a default capacity of 10, with a growth of 0 public
Vector () {This
(default_size, 0);
}
Creates an array of user-specified capacity with a growth rate of 0 public
Vector (int capacity) {This
(capacity, 0);
}
Creates an array of the specified capacity size, setting the amount of growth. If the growth rate is not positive, expansion will expand twice times the public
Vector (int capacity, int capacityincrement) {
if (capacity < 0) {
throw new Ill Egalargumentexception ("Capacity < 0:" + capacity);
}
Elementdata = Newelementarray (capacity);
Elementcount = 0;
This.capacityincrement = capacityincrement;
}
Creates an array of the specified collection
, public Vector (COLLECTION< extends e> c) {
//number of groups, assigned
elementdata = C.toarray (); C20/>elementcount = elementdata.length;
C.toarray might (incorrectly) not return object[] (=
=//may have this magical bug, recreate with 6260652, copy
if (el Ementdata.getclass ()!= object[].class)
elementdata = arrays.copyof (Elementdata, Elementcount, Object[].class);
}
An internal method that returns a new array:
Private e[] Newelementarray (int size) {return
(e[]) new object[size];
Vector method of membership
1. First Look at the 3 modes of expansion of the Vector in JDK 7:
Expands according to the specified capacity private void grow (int newcapacity) {//Creates a new array of the specified capacity, where the specified capacity is more e[than the current array element number NewData = Newelementar
Ray (newcapacity);
Copies the current array to the newly created array system.arraycopy (elementdata, 0, NewData, 0, Elementcount);
The current array points to the new array elementdata = NewData;
}//default growth of one-times expansion private void Growbyone () {int adding = 0;
Capacity capacityincrement is not greater than 0, it increases by one times if (capacityincrement <= 0) {if (adding = elementdata.length) = = 0) {
adding = 1;
} else {//otherwise adding = capacityincrement by volume expansion;
//Create a new array, the size of the current capacity plus adding e[] NewData = Newelementarray (elementdata.length + adding);
copying, assigning system.arraycopy (elementdata, 0, NewData, 0, Elementcount);
Elementdata = NewData;
}//Specify the capacity of the default expansion private void Growby (int required) {int adding = 0; Capacity capacityincrement not greater than 0 if (capacityincrement <= 0) {//If there are no elements in the current array, enlarge if (adding = E
lementdata.length) = = 0) {adding = required;
//Increase the number of expansions to the specified above while (adding < required) {adding + = adding;
} else {//capacity is greater than 0, or the specified number of capacity to go ah adding = (required/capacityincrement) * capacityincrement; However, there may also be deviations, because it is int doing division, so the expansion value is at least a specified volume of more than one times if (adding < required) {adding = Capacityincrement
;
}//Create, copy, assign value one-stop e[] NewData = Newelementarray (elementdata.length + adding);
System.arraycopy (elementdata, 0, NewData, 0, Elementcount);
Elementdata = NewData;
}
2. (Can I say the first mistake, as a JDK7--) then look at the expansion mechanism in JDK 8 and become a kind of:
Expansion, incoming minimum capacity, is similar to Arraylist.grow (int), but expands to different
private void grow (int mincapacity) {
int oldcapacity = Elementdata.length;
If the growth capacityincrement is not greater than 0, expand the capacity of twice times
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);
}
private static int hugecapacity (int mincapacity) {
if (mincapacity < 0)//overflow
throw new Outofmemoryerro R ();
Return (Mincapacity > max_array_size)?
Integer.max_value:
max_array_size;
}
5 ways to add elements in 3.Vector
Expansion precursor, check quantity private void Ensurecapacityhelper (int mincapacity) {if (Mincapacity-elementdata.length > 0)
Grow (mincapacity);
///Inserts an element at the specified location, synchronized public synchronized void Insertelementat (E obj, int index) {modcount++;
if (Index > Elementcount) {throw new ArrayIndexOutOfBoundsException (index
+ ">" + elementcount);
} ensurecapacityhelper (Elementcount + 1);
After the expansion, the elements behind the insertion point are unified and then moved one system.arraycopy (elementdata, index, Elementdata, index + 1, elementcount-index);
Assigned value elementdata[index] = obj;
elementcount++;
}//tail insert element, synchronized public synchronized void addelement (E obj) {modcount++;
Ensurecapacityhelper (Elementcount + 1);
elementdata[elementcount++] = obj;
public void Add (int index, E element) {Insertelementat (element, index);}
Add a collection to the tail, synchronized public synchronized Boolean addall (collection<? extends e> c) {modcount++; Group Object[] A= C.toarray ();
int numnew = A.length;
Expansion, copied to the back of the array ensurecapacityhelper (Elementcount + numnew);
System.arraycopy (A, 0, Elementdata, Elementcount, numnew);
Elementcount + = numnew;
return numnew!= 0;
//Add a combination to the specified location, sync the 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 = A.length;
Ensurecapacityhelper (Elementcount + numnew);
How many elements to move int nummoved = Elementcount-index;
if (nummoved > 0)//move the element behind the insertion position so many bits system.arraycopy (elementdata, index, elementdata, index + numnew,
nummoved);
Copy elements into array system.arraycopy (A, 0, Elementdata, index, numnew);
Elementcount + = numnew;
return numnew!= 0;
}
And finally, there's a Listiterator add method.
public void Add (e e) {
int i = cursor;
Synchronized (vector.this) {
checkforcomodification ();
Vector.this.add (i, e);
Expectedmodcount = Modcount;
}
cursor = i + 1;
Lastret =-1;
}
9 ways to delete in 4.Vector
Deletes the element at the specified location, synchronized 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) {//move the element behind the deletion position forward one system.arraycopy (elementdata, index + 1, elementdata, index, J);
} elementcount--; The last redundant position is null elementdata[elementcount] = NULL;
* To let the GC do its work////delete the specified element, synchronized public synchronized Boolean removeelement (Object obj) {modcount++;
int i = indexOf (obj);
if (I >= 0) {removeelementat (i);
return true;
return false;
} E elementdata (int index) {return (E) Elementdata[index];}
Deletes the element public at the specified location, synchronized E Remove (int index) {modcount++; if (Index >= ElementcounT) throw new ArrayIndexOutOfBoundsException (index);
E OldValue = elementdata (index);
After the deletion of the element is found, the number of elements behind it needs to be moved forward by an int nummoved = elementcount-index-1;
if (nummoved > 0)//Migrate a system.arraycopy (Elementdata, index+1, Elementdata, Index,
nummoved); The last position is null, does not waste space elementdata[--elementcount] = null;
Let GC does its work return oldValue;
public boolean remove (Object o) {return removeelement (o);} Deletes all elements of the specified collection, synchronized public synchronized Boolean removeall (collection<?> c) {//Direct call to Abstractcollection RemoveAll
method, remove return Super.removeall (c) with iterators;
}//Delete all elements, synchronized public synchronized void Removeallelements () {modcount++;
To be NULL, let GC does its work for (int i = 0; i < Elementcount; i++) elementdata[i] = null;
Elementcount = 0;
}//delete the specified range of elements, synchronized protected synchronized void RemoveRange (int fromindex, int toindex) {modcount++; Move the elements from the end position forward to the specified numberposition, covering int nummoved = Elementcount-toindex;
System.arraycopy (Elementdata, Toindex, Elementdata, Fromindex, nummoved);
Place the excess position as a null int newelementcount = Elementcount-(toindex-fromindex);
while (Elementcount!= newelementcount) elementdata[--elementcount] = null;
//witch-hunt, synchronized public synchronized Boolean retainall (collection<?> c) {return super.retainall (c);} JDK 1.8 New Public Synchronized Boolean Removeif (predicate<. Super e> Filter) {Objects.requirenonnull (filter)
;
Add Removeset int removecount = 0 for the content you want to delete;
final int size = Elementcount;
Final Bitset removeset = new Bitset (size);
Final int expectedmodcount = Modcount; for (int i=0; modcount = = Expectedmodcount && i < size; i++) {@SuppressWarnings ("unchecked") f
Inal e element = (e) elementdata[i];
if (filter.test (Element)) {Removeset.set (i);
removecount++;
} } if (Modcount!= expectedmodcount) {throw new concurrentmodificationexception ();
}//Traversal, delete final Boolean anytoremove = removecount > 0;
if (anytoremove) {final int newsize = Size-removecount; for (int i=0, j=0; (I < size) && (J < newsize);
i++, J + +) {i = Removeset.nextclearbit (i);
ELEMENTDATA[J] = Elementdata[i]; for (int k=newsize; k < size; k++) {elementdata[k] = null;
Let GC does its work} elementcount = newsize;
if (Modcount!= expectedmodcount) {throw new concurrentmodificationexception ();
} modcount++;
return anytoremove;
}
Write "synchronized" written hand cramps, or statistics is not synchronized method--. 5. Modifying methods in Vector
Modifies the specified location for the specified element public synchronized E set (int index, E element) {if (index >= elementcount) throw new Arrayi
Ndexoutofboundsexception (index);
Find this element and set the new value directly E OldValue = Elementdata (index);
Elementdata[index] = element;
return oldValue; //Modify the specified location for the specified element public synchronized void Setelementat (E obj, int index) {if (index >= elementcount) {THR
ow new ArrayIndexOutOfBoundsException (index + ">=" + elementcount);
}//array is convenient, direct update is good elementdata[index] = obj;
///modify array capacity public synchronized void setSize (int newsize) {modcount++;
The number of elements exceeds the capacity to enlarge the IF (NewSize > Elementcount) {ensurecapacityhelper (newsize); else {//new elementcount-newsize element for (int i = newsize; i < Elementcount; i++) {E
Lementdata[i] = null;
} elementcount = newsize; }//Sort, modify order public synchronized void sort (comparator<? Super E>
c) {final int expectedmodcount = Modcount;
Used is Arrays.sort Arrays.sort ((e[)) elementdata, 0, Elementcount, c);
if (Modcount!= expectedmodcount) {throw new concurrentmodificationexception ();
} modcount++;
}//Reduce the size of the array, reducing the resource usage public synchronized void TrimToSize () {modcount++;
int oldcapacity = Elementdata.length;
if (Elementcount < oldcapacity) {//new small dot array, assign value Elementdata = arrays.copyof (Elementdata, Elementcount);
}
}
6 query in Vector
Find o position for first occurrence of index starting at specified location public synchronized int indexOf (Object o, int index) {if (o = = null) {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;
//Find o position for the first occurrence in the array public int indexOf (Object o) {return indexOf (o, 0);}
Contains O public boolean contains (Object O) {return indexOf (o, 0) >= 0;} Whether to include the entire collection public synchronized Boolean containsall (collection<?> c) {//Call abstractcollection method, iterate through the lookup with an iterator, dual
Loop return Super.containsall (c); The//first element, in fact, provides a get () method is enough to public synchronized E firstelement () {if (Elementcount = 0) {throw new Nosuche
Lementexception ();
Return Elementdata (0); //The last element, in fact, provides a get () method is enough for public synchronized E lastelement () {if (Elementcount = 0) {throw new NosuChelementexception ();
Return Elementdata (elementCount-1);
Public synchronized Boolean IsEmpty () {return elementcount = = 0;}
Actually contains the number of elements public synchronized int size () {return elementcount;}
Array size, >= element number public synchronized int capacity () {return elementdata.length;}
7. Vector can also be transferred to a group
Public synchronized object[] ToArray () {return
arrays.copyof (Elementdata, Elementcount);
}
Just like ArrayList. Public
synchronized <T> t[] ToArray (t[] a) {
if (A.length < Elementcount) return
( T[]) arrays.copyof (Elementdata, Elementcount, A.getclass ());
System.arraycopy (elementdata, 0, a, 0, elementcount);
if (A.length > Elementcount)
a[elementcount] = null;
return A;
}
8. iterators in Vectors
General iterator iterator:
Public synchronized iterator<e> iterator () {return new Itr ();} Private class Itr implements iterator<e> {int cursor; Index of next element to return int lastret =-1; Index of the last element returned;
-1 if no such int expectedmodcount = Modcount;
public Boolean Hasnext () {//Check return cursor!= elementcount before calling next (); Public E Next () {//note, the Vector-iterator method also adds a synchronous synchronized (vector.this) {Checkforcomodi
Fication ();
int i = cursor;
if (i >= elementcount) throw new Nosuchelementexception ();
cursor = i + 1;
Return Elementdata (Lastret = i);
} public void Remove () {if (Lastret = 1) throw new IllegalStateException ();
Note that the Vector-iterator method also adds synchronous synchronized (vector.this) {checkforcomodification ();
Vector.this.remove (Lastret); ExpeCtedmodcount = Modcount;
} cursor = Lastret;
Lastret =-1; //Probably look at this 1.8 method @Override public void Foreachremaining (consumer<. Super e> action) {Objects
. Requirenonnull (action);
Synchronized (vector.this) {final int size = Elementcount;
int i = cursor;
if (i >= size) {return;
} @SuppressWarnings ("Unchecked") Final e[] Elementdata = (e[)) Vector.this.elementData;
if (i >= elementdata.length) {throw new concurrentmodificationexception ();
while (i!= size && modcount = = Expectedmodcount) {action.accept (elementdata[i++));
}//Update once at the iteration to reduce heap write traffic cursor = i;
Lastret = i-1;
Checkforcomodification ();
} final void Checkforcomodification () { if (Modcount!= expectedmodcount) throw new Concurrentmodificationexception ();
}
}
Listiterator:
Public synchronized listiterator<e> listiterator (int index) {if (Index < 0 | | index > ELEMENTCOUNT)
throw new Indexoutofboundsexception ("Index:" +index);
return new Listitr (index);
Final class Listitr extends Itr implements listiterator<e> {listitr (int index) {super ();
cursor = index;
public Boolean hasprevious () {return cursor!= 0;
public int Nextindex () {return cursor;
public int Previousindex () {return cursor-1;
Public E Previous () {synchronized (vector.this) {checkforcomodification ();
int i = cursor-1;
if (I < 0) throw new nosuchelementexception ();
cursor = i;
Return Elementdata (Lastret = i);
The public void set (E e) {if (Lastret = 1) throw new IllegalStateException (); Synchronized (vector.this) {CHECKforcomodification ();
Vector.this.set (Lastret, E);
} public void Add (e e) {int i = cursor;
Synchronized (vector.this) {checkforcomodification ();
Vector.this.add (i, E);
Expectedmodcount = Modcount;
} cursor = i + 1;
Lastret =-1;
}//1.8 New Skip ... There is also a sort method where the collection you pass in needs to implement the comparer @SuppressWarnings ("unchecked") @Override public synchronized void sort (comparator<).
Super E> C) {final int expectedmodcount = Modcount;
Arrays.sort ((e[]) elementdata, 0, Elementcount, c);
if (Modcount!= expectedmodcount) {throw new concurrentmodificationexception ();
} modcount++;
}
Vector also supports enumeration iterations:
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 < Elementcount) {return
elementdata ( count++);
}
throw new Nosuchelementexception ("Vector enumeration");
}
Summary
Vector featuresThe bottom layer consists of a vector that can grow by capacity (capacity) and capacityincrement (growth quantity) to minimize space expansion by default twice times better to increase the Vector capacity before inserting a large number of elements, which can reduce the The number of times the iterator obtained through iterator and Lastiterator is the fail-fast of the old version of the iterator enumeration is not Fail-fast synchronization class, each method has a synchronous lock before Synchroni Zed, after JDK 2.0, was optimized and Vector joined the Java set framework. Large family
Vector VS ArrayList
In common: Both arrays support random access the default capacity is 10 all have the expansion mechanism
Difference: Vector was born earlier, JDK 1.0 was born, ArrayList JDK 1.2 came out. Vector is more than ArrayList one iterator enumeration vector is thread safe, ArrayList is not Vect or default expansion of twice times, ArrayList is 1.5
If there is no thread-safe requirement, it is generally recommended to use ArrayList, rather than vectors, because it is too inefficient to acquire locks each time. Thanks
Https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html
http://blog.csdn.net/u011518120/article/details/52192680