vector是矢量队列,它继承了abstractlist,实现了list、 randomaccess, cloneable, java.io.serializable接口。
vector接口依赖图:
vector继承了abstractlist,实现了list,它是一个队列,因此实现了相应的添加、删除、修改、遍历等功能。
vector实现了randomaccess接口,因此可以随机访问。
vector实现了cloneable,重载了clone()方法,因此可以进行克隆。
vector实现了serializable接口,因此可以进行序列化。
vector的操作是线程安全的。
vector的数据结构和arraylist差不多,包含了3个成员变量:elementdata,elementcount,capacityincrement。
(1)elementdata是object[]的数组,初始大小为10,会不断的增长。
(2)elementcount是元素的个数。
(3)capacityincrement是动态数组增长的系数。
vector有四种遍历方式:
(1)第一种通过迭代器遍历,即通过iterator去遍历
integer value=iterator iter=vector.iterator()(iter.hasnext())
{
value=(interger)iter.next()}
(2)第二种随机访问,通过索引进行遍历
integer value=size=vector.size()(i=i
(3)第三种通过for循环的方式
integer value=( integer intevector)
{
value=inte}
(4)第四种,enumeration遍历
integer value=enumeration enu=vector.elements()(enu.hasmoreelements())
{
value=(integer)enu.nextelement()}
vector示例代码:
hello {
(string[] args) {
vector vec = vector()vec.add()vec.add()vec.add()vec.add()vec.add()vec.set()vec.add()system..println(+vec)system..println(+vec.indexof())system..println(+vec.lastindexof())system..println(+vec.firstelement())system..println(+vec.elementat())system..println(+vec.lastelement())system..println(+vec.size())system..println(+vec.capacity())system..println(+vec.sublist())enumeration enu = vec.elements()(enu.hasmoreelements())
{
system..println(+enu.nextelement()) vector retainvec = vector() retainvec.add() retainvec.add() system..println(+vec.retainall(retainvec)) system..println(+vec) string[] arr = (string[]) vec.toarray(string[])(string str:arr)
system..println(+str) vec.clear() vec.removeallelements() system..println(+vec.isempty()) }
}
}
vector源代码:
public class vector<e> extends abstractlist<e>
implements list<e>, randomaccess, cloneable, java.io.serializable
{
protected object[] elementdata;//对象数组,来存放数据
protected int elementcount; //当前的数据数目
protected int capacityincrement; //容量增长
private static final long serialversionuid = -2767605614048989439l; //序列号
//构造函数矢量队列初始化大小和增长大小
public vector(int initialcapacity, int capacityincrement) {
super();
if (initialcapacity < 0)
throw new illegalargumentexception("illegal capacity: "+
initialcapacity);
this.elementdata = new object[initialcapacity];
this.capacityincrement = capacityincrement;
}
//构造函数初始化大小
public vector(int initialcapacity) {
this(initialcapacity, 0);
}
//构造函数默认初始化大小10
public vector() {
this(10);
}
//带有集合参数的构造函数
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);
}
//线程安全的对象数组拷贝
public synchronized void copyinto(object[] anarray) {
system.arraycopy(elementdata, 0, anarray, 0, elementcount);
}
//调整容量大小适合当前矢量队列的大小
public synchronized void trimtosize() {
modcount++;
int oldcapacity = elementdata.length;
if (elementcount < oldcapacity) {
elementdata = arrays.copyof(elementdata, elementcount);
}
}
//增加矢量队列的容量大小
public synchronized void ensurecapacity(int mincapacity) {
if (mincapacity > 0) {
modcount++;
ensurecapacityhelper(mincapacity);
}
}
private void ensurecapacityhelper(int mincapacity) {
// overflow-conscious code
if (mincapacity - elementdata.length > 0)
grow(mincapacity);
}
private static final int max_array_size = integer.max_value - 8;
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);
}
private static int hugecapacity(int mincapacity) {
if (mincapacity < 0) // overflow
throw new outofmemoryerror();
return (mincapacity > max_array_size) ?
integer.max_value :
max_array_size;
}
//调整大小,如果超出了就删掉多余的对象
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;
}
//矢量对象的容量
public synchronized int capacity() {
return elementdata.length;
}
//矢量队列的大小
public synchronized int size() {
return elementcount;
}
//是否为空
public synchronized boolean isempty() {
return elementcount == 0;
}
//生成enumeration对象,进行遍历
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");
}
};
}
//判断是否包含某个对象
public boolean contains(object o) {
return indexof(o, 0) >= 0;
}
//返回某个对象的下标
public int indexof(object o) {
return indexof(o, 0);
}
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;
}
//最后出现的对象的坐标
public synchronized int lastindexof(object o) {
return lastindexof(o, elementcount-1);
}
public synchronized int lastindexof(object o, int index) {
if (index >= elementcount)
throw new indexoutofboundsexception(index + " >= "+ elementcount);
if (o == null) {
for (int i = index; i >= 0; i--)
if (elementdata[i]==null)
return i;
} else {
for (int i = index; i >= 0; i--)
if (o.equals(elementdata[i]))
return i;
}
return -1;
}
//返回某个坐标的节点
public synchronized e elementat(int index) {
if (index >= elementcount) {
throw new arrayindexoutofboundsexception(index + " >= " + elementcount);
}
return elementdata(index);
}
//第一个元素
public synchronized e firstelement() {
if (elementcount == 0) {
throw new nosuchelementexception();
}
return elementdata(0);
}
//最后一个元素
public synchronized e lastelement() {
if (elementcount == 0) {
throw new nosuchelementexception();
}
return elementdata(elementcount - 1);
}
//对下标为index的元素替换为obj
public synchronized void setelementat(e obj, int index) {
if (index >= elementcount) {
throw new arrayindexoutofboundsexception(index + " >= " +
elementcount);
}
elementdata[index] = obj;
}
//删除某个下标的元素
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 do its work */
}
//在index坐标后添加obj
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++;
}
//矢量队列末尾添加元素
public synchronized void addelement(e obj) {
modcount++;
ensurecapacityhelper(elementcount + 1);
elementdata[elementcount++] = obj;
}
//删除obj元素
public synchronized boolean removeelement(object obj) {
modcount++;
int i = indexof(obj);
if (i >= 0) {
removeelementat(i);
return true;
}
return false;
}
//清空所有元素
public synchronized void removeallelements() {
modcount++;
// let gc do its work
for (int i = 0; i < elementcount; i++)
elementdata[i] = null;
elementcount = 0;
}
//克隆
public synchronized object clone() {
try {
@suppresswarnings("unchecked")
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(e);
}
}
//生成数组
public synchronized object[] toarray() {
return arrays.copyof(elementdata, elementcount);
}
@suppresswarnings("unchecked")
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;
}
@suppresswarnings("unchecked")
e elementdata(int index) {
return (e) elementdata[index];
}
//得到index的元素
public synchronized e get(int index) {
if (index >= elementcount)
throw new arrayindexoutofboundsexception(index);
return elementdata(index);
}
//将index元素替换成element
public synchronized e set(int index, e element) {
if (index >= elementcount)
throw new arrayindexoutofboundsexception(index);
e oldvalue = elementdata(index);
elementdata[index] = element;
return oldvalue;
}
//矢量队列队尾添加元素
public synchronized boolean add(e e) {
modcount++;
ensurecapacityhelper(elementcount + 1);
elementdata[elementcount++] = e;
return true;
}
//删除对象
public boolean remove(object o) {
return removeelement(o);
}
//在index处添加元素
public void add(int index, e element) {
insertelementat(element, index);
}
//删除index处元素
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,
nummoved);
elementdata[--elementcount] = null; // let gc do its work
return oldvalue;
}
//清空元素
public void clear() {
removeallelements();
}
//判断vector中是否含有所有的collection
public synchronized boolean containsall(collection<?> c) {
return super.containsall(c);
}
//将collection添加到矢量队列的队尾
public synchronized boolean addall(collection<? extends e> c) {
modcount++;
object[] a = c.toarray();
int numnew = a.length;
ensurecapacityhelper(elementcount + numnew);
system.arraycopy(a, 0, elementdata, elementcount, numnew);
elementcount += numnew;
return numnew != 0;
}
//删除包含collection的元素
public synchronized boolean removeall(collection<?> c) {
return super.removeall(c);
}
//删除不存在collection的元素
public synchronized boolean retainall(collection<?> c) {
return super.retainall(c);
}
//在某个index之后追加集合
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);
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;
}
//判断矢量队列是否相同
public synchronized boolean equals(object o) {
return super.equals(o);
}
//返回hashcode
public synchronized int hashcode() {
return super.hashcode();
}
//
public synchronized string tostring() {
return super.tostring();
}
//切断
public synchronized list<e> sublist(int fromindex, int toindex) {
return collections.synchronizedlist(super.sublist(fromindex, toindex),
this);
}
//删除范围
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;
}
//序列化
private void writeobject(java.io.objectoutputstream s)
throws java.io.ioexception {
final java.io.objectoutputstream.putfield fields = s.putfields();
final object[] data;
synchronized (this) {
fields.put("capacityincrement", capacityincrement);
fields.put("elementcount", elementcount);
data = elementdata.clone();
}
fields.put("elementdata", data);
s.writefields();
}
//迭代
public synchronized listiterator<e> listiterator(int index) {
if (index < 0 || index > elementcount)
throw new indexoutofboundsexception("index: "+index);
return new listitr(index);
}
public synchronized listiterator<e> listiterator() {
return new listitr(0);
}
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 last element returned; -1 if no such
int expectedmodcount = modcount;
public boolean hasnext() {
// racy but within spec, since modifications are checked
// within or after synchronization in next/previous
return cursor != elementcount;
}
public e next() {
synchronized (vector.this) {
checkforcomodification();
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();
synchronized (vector.this) {
checkforcomodification();
vector.this.remove(lastret);
expectedmodcount = modcount;
}
cursor = lastret;
lastret = -1;
}
@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 end of iteration to reduce heap write traffic
cursor = i;
lastret = i - 1;
checkforcomodification();
}
}
final void checkforcomodification() {
if (modcount != expectedmodcount)
throw new concurrentmodificationexception();
}
}
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);
}
}
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;
}
}
@override
public synchronized void foreach(consumer<? super e> action) {
objects.requirenonnull(action);
final int expectedmodcount = modcount;
@suppresswarnings("unchecked")
final e[] elementdata = (e[]) this.elementdata;
final int elementcount = this.elementcount;
for (int i=0; modcount == expectedmodcount && i < elementcount; i++) {
action.accept(elementdata[i]);
}
if (modcount != expectedmodcount) {
throw new concurrentmodificationexception();
}
}
@override
@suppresswarnings("unchecked")
public synchronized boolean removeif(predicate<? super e> filter) {
objects.requirenonnull(filter);
// figure out which elements are to be removed
// any exception thrown from the filter predicate at this stage
// will leave the collection unmodified
int removecount = 0;
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")
final e element = (e) elementdata[i];
if (filter.test(element)) {
removeset.set(i);
removecount++;
}
}
if (modcount != expectedmodcount) {
throw new concurrentmodificationexception();
}
// shift surviving elements left over the spaces left by removed elements
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 do its work
}
elementcount = newsize;
if (modcount != expectedmodcount) {
throw new concurrentmodificationexception();
}
modcount++;
}
return anytoremove;
}
@override
@suppresswarnings("unchecked")
public synchronized void replaceall(unaryoperator<e> operator) {
objects.requirenonnull(operator);
final int expectedmodcount = modcount;
final int size = elementcount;
for (int i=0; modcount == expectedmodcount && i < size; i++) {
elementdata[i] = operator.apply((e) elementdata[i]);
}
if (modcount != expectedmodcount) {
throw new concurrentmodificationexception();
}
modcount++;
}
@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++;
}
@override
public spliterator<e> spliterator() {
return new vectorspliterator<>(this, null, 0, -1, 0);
}
/** similar to arraylist spliterator */
static final class vectorspliterator<e> implements spliterator<e> {
private final vector<e> list;
private object[] array;
private int index; // current index, modified on advance/split
private int fence; // -1 until used; then one past last index
private int expectedmodcount; // initialized when fence set
/** create new spliterator covering the given range */
vectorspliterator(vector<e> list, object[] array, int origin, int fence,
int expectedmodcount) {
this.list = list;
this.array = array;
this.index = origin;
this.fence = fence;
this.expectedmodcount = expectedmodcount;
}
private int getfence() { // initialize on first use
int hi;
if ((hi = fence) < 0) {
synchronized(list) {
array = list.elementdata;
expectedmodcount = list.modcount;
hi = fence = list.elementcount;
}
}
return hi;
}
public spliterator<e> trysplit() {
int hi = getfence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null :
new vectorspliterator<e>(list, array, lo, index = mid,
expectedmodcount);
}
@suppresswarnings("unchecked")
public boolean tryadvance(consumer<? super e> action) {
int i;
if (action == null)
throw new nullpointerexception();
if (getfence() > (i = index)) {
index = i + 1;
action.accept((e)array[i]);
if (list.modcount != expectedmodcount)
throw new concurrentmodificationexception();
return true;
}
return false;
}
@suppresswarnings("unchecked")
public void foreachremaining(consumer<? super e> action) {
int i, hi; // hoist accesses and checks from loop
vector<e> lst; object[] a;
if (action == null)
throw new nullpointerexception();
if ((lst = list) != null) {
if ((hi = fence) < 0) {
synchronized(lst) {
expectedmodcount = lst.modcount;
a = array = lst.elementdata;
hi = fence = lst.elementcount;
}
}
else
a = array;
if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
while (i < hi)
action.accept((e) a[i++]);
if (lst.modcount == expectedmodcount)
return;
}
}
throw new concurrentmodificationexception();
}
public long estimatesize() {
return (long) (getfence() - index);
}
public int characteristics() {
return spliterator.ordered | spliterator.sized | spliterator.subsized;
}
}
}
以上就是java集合之vector具体代码分析(图)的详细内容。