其实Vector底层和ArrayList底层差不多,就是多了synchronized,大部分还是一样的
import java.util.Arrays;
public class VectorTest<E> implements java.io.Serializable {
Object[] elementData;
int elementCount;
int capacityIncrement;
int MAX_ARRAY_SIZE=Integer.MAX_VALUE-8;
public VectorTest(int initialCapacity,int capacityIncrement) {
if (initialCapacity<0)
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
this.elementData=new Object[initialCapacity];
this.capacityIncrement=capacityIncrement;
}
public VectorTest(int initialCapacity) {
//调用上面那个构造方法
this(initialCapacity,0);
}
public VectorTest() {
this(10);
}
public synchronized boolean add(E e) {
ensureCapacityHelper(elementCount+1);
elementData[elementCount++]=e;
return true;
}
public synchronized E get(int index) {
if(index>=elementCount)
throw new ArrayIndexOutOfBoundsException();
return (E)elementData[index];
}
public synchronized E set(int index,E element) {
if(index>=elementCount)
throw new ArrayIndexOutOfBoundsException();
E oldVal=(E)elementData[index];
elementData[index]=element;
return oldVal;
}
public boolean remove(Object o) {
return removeElement(o);
}
public synchronized boolean removeElement(Object o) {
//获取到元素的下标
int i=indexOf(o,0);
if(i>=0) {
//将该元素后面的元素都往前移,使用arraycopy方法
removeElementAt(i);
return true;
}
return false;
}
public synchronized void removeElementAt(int index) {
if(index>=elementCount||index<0)
throw new ArrayIndexOutOfBoundsException();
//这些元素都是需要移动的
int j=elementCount-index-1;
if(j>0) {
System.arraycopy(elementData,index+1,elementData,index,j);
}
elementCount--;
elementData[elementCount]=null;
}
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 void ensureCapacityHelper(int minCapacity) {
//如果数组最小要求长度大于数组现在的长度,就需要扩容
if(minCapacity-elementData.length>0) {
grow(minCapacity);
}
}
public void grow(int minCapacity) {
int oldCapacity=elementData.length;
//要根据设置的每次扩容的大小来进行扩容,如果设置的步长大于0,则就加上步长,否则,就是扩大二倍
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);
}
public int hugeCapacity(int minCapacity) {
if(minCapacity<0)
throw new OutOfMemoryError();
return (minCapacity>MAX_ARRAY_SIZE?Integer.MAX_VALUE:MAX_ARRAY_SIZE);
}
}