1.继承与实现体系:
2. vector简单介绍
vector与ArrayList一样,同属于AbstractLists的子类,但与ArrayList不同的是,它对于内部对元素的操作方法都是同步的,即线程安全的,但随之而来的就是效率问题,它的操作效率会略低于ArrayList
3 vector的主要属性介绍:
//vector内部维护的数组,用于储存元素
protected Object[] elementData;
//存储元素的长度大小
protected int elementCount;
//扩容增长量,默认是0,当是0时,每次扩容按原量的1倍扩;若大于0,就按该量来扩容
protected int capacityIncrement;
4.vector的构造方法:
//确定初始容量的大小,及扩容增长量
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
//确定初始容量大小,并设置扩容增长量为0,这种情况下,每次扩容会扩容至原来的2倍
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
//无参构造方法,设置初容量大小为10
public Vector() {
this(10);
}
//将集合复制给elementData
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);
}
5.Vector的增删方法介绍:
add(E e);
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
- 首先,操作次数加一
- 调用ensureCapacityHelper(int minCapacity),参数为当前元素的数量加一
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
该方法是判断是否需要扩容,如果增长之后的元素数量大于数组的大小,即需要扩容,调用grow(int minCapacity)方法
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);
}
该方法就是扩容的方法,这里就用到了之前构造函数指定的扩容增长量:①capacityIncrement 。如果该量大于0,就增加该量的大小;如果该量小于等于0,则扩容至原量的2倍
②如果扩容之后的量还是小于添加元素之后的容量大小,就扩容至增加元素之后的容量大小
③复制数组
- 将元素赋到数组中
remove(Object o)
public boolean remove(Object o) {
return removeElement(o);
}
public synchronized boolean removeElement(Object obj) {
modCount++;
int i = indexOf(obj);
if (i >= 0) {
removeElementAt(i);
return true;
}
return false;
}
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 */
}
跟ArrayList一样,最重要的就是理解扩容机制。
删除方法跟增加方法差不多,都是通过复制数组的方式对元素进行操作,而这里就是ArrayList、vector与LinkedList对于增删操作效率差异的原因了。