Vector特点:
1.内部通过数组实现
2.通过synchronized同步方法,线程安全,适合多线程
3.由于线程安全,效率不高
4.默认存放10个元素
5.需要增加容量时候,默认新增加容量是元素Vector的大小
6.效率低,不推荐用
所在包
package java.util;
继承AbstractList
实现List 、RandomAccess、Cloneable、java.io.Serializable
Clone:
简单的说就是clone一个对象实例。使得clone出来的copy和原有的对象一模一样
Serializable:
序列化
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
// 内部代码下面讲解
}
内部通过Object数组存放元素
protected Object[] elementData;
当前元素id
protected int elementCount;
每次可增加容量大小
protected int capacityIncrement;
use serialVersionUID from JDK 1.0.2 for interoperability
private static final long serialVersionUID = -2767605614048989439L;
构造器
initialCapacity:默认大小
capacityIncrement:可增加容量大小
/** @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
构造器
/* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
构造器
默认只能存放10个元素
public Vector() {
this(10);
}
构造器
利用集合c构建Vector
/* @throws NullPointerException if the specified collection is null
* @since 1.2
*/
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);
}
下面方法都加了synchronized,保证线程安全
elementData内元素复制到anArray中
/* @throws NullPointerException if the given array is null
* @throws IndexOutOfBoundsException if the specified array is not
* large enough to hold all the components of this vector
* @throws ArrayStoreException if a component of this vector is not of
* a runtime type that can be stored in the specified array
* @see #toArray(Object[])
*/
public synchronized void copyInto(Object[] anArray) {
System.arraycopy(elementData, 0, anArray, 0, elementCount);
}
修剪elementData,保证其内部的元素都是有效元素
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);//是否需要增加容量
}
}
根据Vector长度和判断是否需要增加容量
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)// true 增加容量
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;
}
可以看出:当不指定扩充容量的最小值时候,每次新增加的容量大小等于原始Vector的大小
设置大小,根据程序,使得newSize以后的元素清楚,只保留newsize个元素。当不足newsize个元素的时候,需要进行扩充
/* @throws ArrayIndexOutOfBoundsException if the new size is negative
*/
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;
}
获取当前Vector的容量
public synchronized int capacity() {
return elementData.length;
}
获取当前Vector元素的个数
public synchronized int size() {
return elementCount;
}
注意两个的区别:
容量可能比较大,个数指的是具体元素的个数
容量只能够存放元素个数的最大值
判断是否为空
public synchronized boolean isEmpty() {
return elementCount == 0;
}
获取一个Enumeration类型的组件,可以顺序的访问Vector元素,这个和迭代器很类似
public Enumeration elements() {
return new Enumeration() {
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");
}
};
}
判断是否包含元素 o
public boolean contains(Object o) {
return indexOf(o, 0) >= 0;
}
返回元素 o 第一次出现的下标
public int indexOf(Object o) {
return indexOf(o, 0);
}
从index开始,查找元素o出现的下标
当不出现的时候返回-1
实现很简单顺序查找,比较是否相等
/* @throws IndexOutOfBoundsException if the specified index is negative
* @see Object#equals(Object)
*/
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;
}
返回元素o最有一次出现的下标
public synchronized int lastIndexOf(Object o) {
return lastIndexOf(o, elementCount-1);
}
截止到index,返回元素o 最后一次出现的下标
不出现,返回-1
/* @throws IndexOutOfBoundsException if the specified index is greater
* than or equal to the current size of this vector
*/
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;
}
返回index位置元素
/* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
*/
public synchronized E elementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
}
return elementData(index);
}
获取第一个元素的值
/* @throws NoSuchElementException if this vector has no components
*/
public synchronized E firstElement() {
if (elementCount == 0) {
throw new NoSuchElementException();
}
return elementData(0);
}
获取最后一个元素的值
/* @throws NoSuchElementException if this vector is empty
*/
public synchronized E lastElement() {
if (elementCount == 0) {
throw new NoSuchElementException();
}
return elementData(elementCount - 1);
}
更新index位置元素
/* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
*/
public synchronized void setElementAt(E obj, int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
elementData[index] = obj;
}
删除index位置的元素
/* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
*/
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) { // elementData数组,从index+1开始复制j个元素,到该数组的index开始位置
System.arraycopy(elementData, index + 1, elementData, index, j);
}
elementCount--; // 元素个数-1
elementData[elementCount] = null; // 空,有利于垃圾回收
}
index位置插入元素 o
/* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index > size()})
*/
public synchronized void insertElementAt(E obj, int index) {
modCount++;
if (index > elementCount) { // 越界
throw new ArrayIndexOutOfBoundsException(index
+ " > " + elementCount);
}
ensureCapacityHelper(elementCount + 1); // 确保可以插入元素
// index - elementCount 之间的元素 后移一位
System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
elementData[index] = obj; // 插入元素
elementCount++; // 元素个数 + 1
}
尾部插入元素
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;
}
clone一个Vector
public synchronized Object clone() {
try {
@SuppressWarnings("unchecked")
Vector v = (Vector) 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();
}
}
Vector元素复制到数组
public synchronized Object[] toArray() {
return Arrays.copyOf(elementData, elementCount);
}
Vector中元素复制到指定数组
/* @throws ArrayStoreException if the runtime type of a is not a supertype
* of the runtime type of every element in this Vector
* @throws NullPointerException if the given array is null
* @since 1.2
*/
@SuppressWarnings("unchecked")
public synchronized 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;
}
获取index位置元素
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
获取index位置元素,可以抛出异常
/* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
* @since 1.2
*/
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
更新index位置元素
/* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
* @since 1.2
*/
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位置插入元素
/* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index > size()})
* @since 1.2
*/
public void add(int index, E element) {
insertElementAt(element, index);
}
删除index位置元素
/* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
* @param index the index of the element to be removed
* @return element that was removed
* @since 1.2
*/
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内是否包含集合c的元素
/* @throws NullPointerException if the specified collection is null
*/
public synchronized boolean containsAll(Collection> c) {
return super.containsAll(c);
}
集合c中元素添加到Vector中
/* @throws NullPointerException if the specified collection is null
* @since 1.2
*/
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;
}
Vector集合 与集合c的差集
/ * @throws NullPointerException if this vector contains one or more null
* elements and the specified collection does not support null
* elements
* or if the specified collection is null
* @since 1.2
*/
public synchronized boolean removeAll(Collection> c) {
return super.removeAll(c);
}
交集
/* @throws NullPointerException if this vector contains one or more null
* elements and the specified collection does not support null
* elements
* or if the specified collection is null
* @since 1.2
*/
public synchronized boolean retainAll(Collection> c) {
return super.retainAll(c);
}
index位置插入集合c的元素
/* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index > size()})
* @throws NullPointerException if the specified collection is null
* @since 1.2
*/
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;
}
重写equals方法
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();
}
返回区间内的元素,并保存在List中
/* @throws IndexOutOfBoundsException if an endpoint index value is out of range
* {@code (fromIndex < 0 || toIndex > size)}
* @throws IllegalArgumentException if the endpoint indices are out of order
* {@code (fromIndex > toIndex)}
*/
public synchronized List 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();
}
获取从index开始的迭代器
/* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public synchronized ListIterator listIterator(int index) {
if (index < 0 || index > elementCount)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
获取所有元素的迭代器
public synchronized ListIterator listIterator() {
return new ListItr(0);
}
获取所有元素的迭代器
public synchronized Iterator iterator() {
return new Itr();
}
ListItr迭代器与Itr迭代器区别
ListItr继承Itr,并增加了前驱遍历的方法,也可以添加元素
Itr只能向后遍历
可以查看下面的代码
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;
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
ListItr
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;
}
}