import java.util.Arrays;
import java.util.RandomAccess;
import jdk.internal.util.ArraysSupport;
/**
* @Classname Vector继承自AbstractList,实现了Stack类
* @note:Vector是线程安全的,ArrayList不是线程安全的
* @note:Vector底层是一个可以增长的数组组成的,通过capacity和capacityIncrement来尽量少的占用空间
* @note:最好在插入大量元素前增加vector容量,那样可以减少重新申请内存的次数
* @note:通过iterator和lastIterator获得的迭代器是fail-fast的
* @note:通过elements获得的Enumeration迭代器不是fail-fast的
* @note:Vector属于同步类,每个方法都有同步锁synchronized
*/
public class Vector<E> extends AbstractList<E>
implements List<E>,RandomAccess,Cloneable,java.io.Serializable{
/**
* vector的成员变量:
*/
protected Object[] elementData; // 底层也是个数组
protected int elementCount; // 数组元素个数
protected int capacityIncrement; // 扩容时增长数量,允许用户设置,如果这个值是0或负数,扩容时会扩大2倍,而不是1.5倍
private static final long serinalVersionUID = -2767605614048989439L;
/**
* vector的构造函数:
*/
public Vector() {
this(10); // this()调用的作用是调用类本身已经存在的其他的构造函数
}
public Vector(int initinalCapacity) {
this(initinalCapacity,0);
}
public Vector(int initinalCapacity, int capacityIncrement) {
super(); // super()调用的是父类的构造函数
if(initinalCapacity<0) {
throw new IllegalArgumentException();
}
this.elementData = new Object[initinalCapacity];
this.capacityIncrement = capacityIncrement;
}
public Vector(Collection<? extends E> c) { // 创建一个包含指定集合的数组
Object[] a = c.toArray();
elementCount = a.length;
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, elementCount,Object[].class);
}
}
/**
** vector的成员方法:扩容机制,会调用ArraysSupport中的newLength方法
**/
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = ArraysSupport.newlength(oldCapacity,minCapacity-oldCapacity,
capacityIncrement>0?capacityIncrement:oldCapacity);// 如果增长量不大于0,就扩容两倍
return elementData = Arrays.copyOf(elementData, newCapacity);
}
private Object[] grow() {
return grow(elementCount+1);
}
// 调用ArraysSupport中的newLength方法
public static final int MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8;
public static int newLength(int oldLength, int minGrowth, int prefGrowth) {
int newLength = Math.max(minGrowth, prefGrowth) + oldLength;
if (newLength - MAX_ARRAY_LENGTH <= 0) {
return newLength;
}
return hugeLength(oldLength, minGrowth);
}
private static int hugeLength(int oldLength, int minGrowth) {
int minLength = oldLength + minGrowth;
if (minLength < 0) {
throw new OutOfMemoryError("Required array length too large");
}
if (minLength <= MAX_ARRAY_LENGTH) {
return MAX_ARRAY_LENGTH;
}
return Integer.MAX_VALUE;
}
/**
** vector的成员方法:5种添加元素的办法
**/
public synchronized void insertElementAt(E obj,int index) {
if (index > elementCount) {
throw new ArrayIndexOutOfBoundsException(index);
}
modCount;
final int s = elementCount;
Object[] elementData = this.elementData;
if(s == elementData.length) {
elementData = grow();// 元素个数等于数组长度时才扩容为2倍
}
// 将该索引的元素及后面的元素整体后移一位
System.arraycopy(elementData, index, elementData, index+1, s-index);
elementData[index] = obj;
elementCount = s+1;
}
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length) {
elementData = grow();
}
elementData[s] = e;
elementCount = s+1;
}
protected transient int modCount = 0;
public synchronized void addElement(E obj) {
modCount++;
add(obj,elementData,elementCount);// 尾部插入元素
}
public void add(int index, E element) {// 从List中实现的方法,方法体中调用的是自己的方法
insertElementAt(element, index);
}
// 添加一个集合到指定位置,同步的
public synchronized boolean addAll(int index, Collection<? extends E> c) {
if (index < 0 || index > elementCount) {
throw new ArrayIndexOutOfBoundsException();
}
Object[] a = c.toArray();
modCount++;
int numNew = a.length;
if (numNew == 0) {
return false;
}
Object[] elementData = this.elementData;
final int s = elementCount;
if (numNew > elementData.length -s) {
elementData = grow(s + numNew);
}
int numMoved = s - index;
if (numMoved > 0) {
System.arraycopy(elementData, index, elementData, index+numNew, numMoved);
}
System.arraycopy(a, 0, elementData, index, numNew);
elementCount = s + numNew;
return true;
}
/**
** vector转换成数组:跟ArrayList一样,完全没必要先转成Iterator再进行操作
**/
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;
}
/**
** vector迭代器内部类:和ArrayList差不多,只不过这里是同步的
**/
private class Itr implements Iterator<E> {
int cursor;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() {
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;
}
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
while (i < size && modCount == expectedModCount)
action.accept(elementAt(es, 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;
}
}
}
数据结构之向量实现
最新推荐文章于 2023-07-19 16:18:35 发布