Vector源码解读

Vector与ArrayList一样,继承了AbstractList类,实现了List等接口

Vector底层为对象数组

Vector是线程同步的,即线程安全,Vector类的操作方法带有synchronized

在开发中,需要线程同步安全时,考虑使用Vector

Vector和ArrayList的比较

底层结构:都是可变数组;

线程同步效率:ArrayList线程不安全,效率高;Vector线程安全,效率不高

扩容倍数:Array1.5倍扩容;Vector如果是无参,默认容量为10,满后,默认按2倍扩容,如果指定大小,则每次直接按2倍扩容

源码

成员变量

protected Object[] elementData;//数组数据
protected int elementCount;//数组大小
protected int capacityIncrement;//容量增量
private static final long serialVersionUID = -2767605614048989439L;//与ArrayList中UID作用一样

构造器

无参

public Vector() {
   this(10);
}

有参

public Vector(int initialCapacity) {
   this(initialCapacity, 0);
}

无参、有参构造终究都会回到这一构造

public Vector(int initialCapacity, int capacityIncrement) {//capacityIncrement在扩容grow方法可以知道,可以自定义扩容大小
   super();
   if (initialCapacity < 0)
       throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
   this.elementData = new Object[initialCapacity];
   this.capacityIncrement = capacityIncrement;
}

第三种有参构造表明,可以将集合传入Vector

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);
  }
}

成员方法(部分)

add
public synchronized boolean add(E e) {
       modCount++;
       ensureCapacityHelper(elementCount + 1);
       elementData[elementCount++] = e;
       return true;
  }
private void ensureCapacityHelper(int minCapacity) {
   // overflow-conscious code
   if (minCapacity - elementData.length > 0)//确定是否需要扩容
       grow(minCapacity);
}
private void grow(int minCapacity) {
   // overflow-conscious code
   int oldCapacity = elementData.length;
   int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                    capacityIncrement : oldCapacity);//首次add时,capacityIncrement为0,返回的是oldCapacity,因此扩容为原elementData数组大小的两倍
   //由三目运算符可知,在构造器传入参数时,可以自己指定每次扩容增加的容量,若自己指定,则不会按照两倍的原则扩容
   if (newCapacity - minCapacity < 0)//当 new Vector(0) 时,elementData数组大小为0,扩容两倍后,仍然为0
       newCapacity = minCapacity;
   if (newCapacity - MAX_ARRAY_SIZE > 0)
       newCapacity = hugeCapacity(minCapacity);//两个if语句与ArrayList一样
   elementData = Arrays.copyOf(elementData, newCapacity);//扩容的底层与ArrayList一样,使用copyOf方法
}//copyOf方法会返回一个指定大小的数组,在之前数组的基础上,尾部添加null

在new Vector()时,相当于调用有参构造,默认传入容量为10

 
posted @   qwdsa019X  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示