首页 > 编程语言 >JDK源码分析-Vector

JDK源码分析-Vector

时间:2024-04-26 18:11:08浏览次数:13  
标签:index JDK int elementData elementCount 源码 数组 public Vector

概述

Vector 是 Java集合中线程安全的动态数组,它也可以根据需要进行扩容和缩容,与 ArrayList 类似。但有一个重要的区别,Vector 是同步的,也就是它的操作是线程安全的,在某些特定场景下是可以保证线程安全的,但同时也会带来性能损耗,因此在单线程环境通常还是推荐使用 ArrayList。

类图

从以上类图可以看到,Vector 实现了四个接口,继承了一个抽象类:

  • List接口,主要提供数组的添加、删除、修改、遍历等操作
  • Cloneable接口,表示Vector支持克隆
  • RandomAccess接口,表示Vector支持快速地随机访问
  • Serializable接口,表示Vector支持序列化功能
  • AbstractList抽象类,主要提供迭代遍历等操作

源码解读

成员变量

// 与 ArrayList 中一致,elementData 是用于存储数据的。
protected Object[] elementData;

// 与ArrayList 中的size 一样,保存数据的个数
protected int elementCount;

// 设置Vector 的增长系数,如果为空,默认每次扩容2倍。
protected int capacityIncrement;

// 数组最大值
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

构造方法

Vector 中提供了三种构造方法:

  • public Vector() 默认构造函数
  • public Vector(int initialCapacity):创建一个有初始化容量的vector集合
  • public Vector(int initialCapacity, int capacityIncrement):创建一个有初始化容量且扩容时增加容量的容量值的vector集合
  • public Vector(Collection<? extends E> c):创建一个包含集合c中所有元素的vector集合

Vector()

public Vector() {
    this(10);
}

默认构造方法,内部调用其它构造方法,初始化容量 10

Vector(int initialCapacity)

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

initialCapacity 初始化容量,内部调用其它构造方法,增量值 0

Vector(int initialCapacity, int capacityIncrement)

public Vector(int initialCapacity, int capacityIncrement) {
    // 调用父类构造函数
    super();
    // 对初始化容量参数进行校验
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    // 创建一个长度为initialCapacity的数组
    this.elementData = new Object[initialCapacity];
    // 自动扩容时增加的容量值
    this.capacityIncrement = capacityIncrement;
}

初始化底层元素数组,增量值

Vector(Collection<? extends E> c)

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

拷贝集合c到底层元素数组,设置元素个数

插入方法

插入元素方法核心主要有以下5个:

  • public synchronized boolean add(E e) :在数组末尾顺序新增一个元素,添加成功返回true,反之
  • public synchronized void addElement(E obj):在数组末尾顺序新增一个元素,没有返回值
  • public void add(int index, E element):在数组指定下标位置新增一个元素
  • public synchronized boolean addAll(Collection<? extends E> c):在数组末尾顺序添加此集合c中所有元素,添加成功返回true,反之
  • public synchronized boolean addAll(int index, Collection<? extends E> c):在数组指定下标位置添加此集合c中所有元素,添加成功返回true,反之

synchronized boolean add(E e)

public synchronized boolean add(E e) {
    // 这是一个自增操作,增加了列表的修改计数。这个计数是用来跟踪列表被修改了多少次,这对于一些并发控制是非常有用的。(可以暂时不用关注)
    modCount++;
    // 确保数组容量 如不足则触发扩容机制
    ensureCapacityHelper(elementCount + 1);
    // 将此元素添加到数组的末尾
    // 个人觉得写为:elementData[elementCount] = e; elementCount++; 更易理解
    elementData[elementCount++] = e;
    return true;
}

同步方法,在数组尾部插入元素,添加成功返回 true。重点分析扩容方法 ensureCapacityHelper:

private void ensureCapacityHelper(int minCapacity) {
    // 最小容量 > 数组长度 的时候触发扩容
    if (minCapacity - elementData.length > 0)
        // 扩容方法
        grow(minCapacity);
}

private void grow(int minCapacity) {
    // 拿到数组长度 也就是旧容量
    int oldCapacity = elementData.length;

    // (capacityIncrement > 0) ? capacityIncrement : oldCapacity
    // 容量增量值 如果大于0 则是capacityIncrement  如果小于等于0 则是oldCapacity
    // 计算新容量: 新容量 = 旧容量 + 容量增量值
    int newCapacity = oldCapacity + 
        ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
    // 个人觉得写为:newCapacity < minCapacity 更易理解
    // 如果这时:新容量 < 最小容量,那么新容量 = 最小容量
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;

    // 个人觉得写为:newCapacity > MAX_ARRAY_SIZE 更易理解
    // private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    // 如果这时:新容量 > 数组最大容量,则触发扩容至更大容量 Integer.MAX_VALUE
    // public static final int MAX_VALUE = 0x7fffffff;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);

    // 根据新的容量 newCapacity 来创建一个新的数组,并将原数组 elementData 的元素复制到新数组中
    elementData = Arrays.copyOf(elementData, newCapacity);
}

扩容的原理与 ArrayList 基本一致,minCapacity > elementData.length 调用 grow 进行扩容。

与 ArrayList 不同的是,新容量的计算。增量值大于0时直接使用增量值,否则使用原数组长度(也就是*2)。

int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                 capacityIncrement : oldCapacity);

synchronized void addElement(E obj)

public synchronized void addElement(E obj) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = obj;
}

同步方法,在数组尾部插入元素,逻辑同 add(E e),区别:无返回值。

void add(int index, E element)

public void add(int index, E element) {
    insertElementAt(element, index);
}

public synchronized void insertElementAt(E obj, int index) {
    modCount++;
    // 校验index下标是否超出数组长度
    if (index > elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " > " + elementCount);
    }
    // 确保数组容量 如不足则触发扩容机制(上文以解读 此处不赘述) 
    ensureCapacityHelper(elementCount + 1);
    // 使用 System.arraycopy 方法进行数组元素的移动。该方法会将从 index 开始的元素向后移动一位,为新元素腾出插入位置。
    System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
    // 在此下标位置处 放入此元素
    elementData[index] = obj;
    // 数组元素总数量+1
    elementCount++;
}

同步方法,在数组指定位置插入元素,核心代码段如下:

System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);

从索引index位置右移一位。

synchronized boolean addAll(Collection<? extends E> c)

public synchronized boolean addAll(Collection<? extends E> c) {
    modCount++;
    // 将集合 c 转化为一个数组 并赋值给临时中转数组 a
    Object[] a = c.toArray();
    int numNew = a.length;
    // 确保数组容量 如不足则触发扩容机制(上文以解读 此处不赘述) 
    ensureCapacityHelper(elementCount + numNew);
    // 使用 System.arraycopy 方法进行数组元素的移动
    System.arraycopy(a, 0, elementData, elementCount, numNew);
    // 数组元素总数量计算
    elementCount += numNew;
    return numNew != 0;
}

同步方法,在数组尾部批量插入元素(集合 c),插入成功返回 true。与单个插入没啥区别,只是这里使用 System.arraycopy 方法,在数组尾部拷贝赋值。

synchronized boolean addAll(int index, Collection<? extends E> c)

public synchronized boolean addAll(int index, Collection<? extends E> c) {
    modCount++;
    // 校验index下标
    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;
}

同步方法,在数组指定位置批量插入元素(集合 c),插入成功返回 true。与尾部批量插入不同的是,这里需要按索引index位置右移 c.length 的长度,然后在索引index位置拷贝赋值。

移除方法

移除方法核心主要有以下5个:

  • public boolean remove(Object o):在数组移除指定元素(首个),移除成功返回 true
  • public synchronized boolean removeElement(Object obj):在数组移除指定元素(首个),移除成功返回 true
  • public synchronized void removeElementAt(int index):在数组移除指定索引元素
  • public synchronized E remove(int index):在数组移除指定索引元素,返回移除元素
  • public synchronized void removeAllElements():移除数组所有元素

boolean remove(Object o)

public boolean remove(Object o) {
    return removeElement(o);
}

removeElement 方法的封装,内部直接调用 removeElement 方法,无逻辑

synchronized boolean removeElement(Object obj)

public synchronized boolean removeElement(Object obj) {
    modCount++;
    int i = indexOf(obj);
    if (i >= 0) {
        removeElementAt(i);
        return true;
    }
    return false;
}

调用 indexOf 方法获取指定元素索引位置,如果索引值大于等于0,调用 removeElementAt 方法删除指定索引元素。

public int indexOf(Object o) {
    return indexOf(o, 0);
}

indexOf 方法的封装,内部直接调用 indexOf 方法,无逻辑。

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

逻辑比较简单,就是遍历查找等于 null 或者 o 的 index。

synchronized void removeElementAt(int index)

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 */
}

首先校验 index 值有效性,然后获取指定索引后继元素个数 j。如果 j大于0表示非最后一个元素,调用 System.arraycopy 方法左移一位。

elementCount--;
elementData[elementCount] = null; /* to let gc do its work */

元素个数减一,将对象引用清除,GC回收。

synchronized E remove(int index)

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

remove方法与removeElementAt方法逻辑基本一致,区别在于remove需要返回移除元素,调用 elementData方法获取指定索引index对应元素。还有一点需要注意,此方法没有判断 index < 0,如果传值错误出现非预期效果。

synchronized void removeAllElements()

public synchronized void removeAllElements() {
    modCount++;
    // Let gc do its work
    for (int i = 0; i < elementCount; i++)
        elementData[i] = null;

    elementCount = 0;
}

方法比较简单,遍历将数组元素引用清除,GC回收,元素个数置为0。 

线程安全性 

Vector 是线程安全的,它实现线程安全的方式也很简单粗暴:直接在方法上使用 synchronized 关键字进行同步。

总结

  • 与 ArrayList 类似,Vector 也可以认为是「可变数组」;
  • 扩容原理与 ArrayList 基本一致,只是新容量计算方式略有不同:指定增长容量时,新容量为旧容量 + 增长容量;否则扩容为旧容量的 2 倍;
  • 线程安全的,实现方式简单(synchronized);
  • Vector相比ArrayList很多方法都使用了synchronized来保证线程安全,这也就意味着每次都需要获得对象同步锁,效率会明显比ArrayList要低;

 

 

参考文章

  • https://blog.csdn.net/weixin_45663027/article/details/134241234

标签:index,JDK,int,elementData,elementCount,源码,数组,public,Vector
From: https://www.cnblogs.com/grassLittle/p/18160221

相关文章

  • Nginx 源码安装
     Nginx官网:https://nginx.org参考:Nginx配置常用参数梳理https://www.jb51.net/server/285538k8k.htmnginx配置参数详解https://blog.csdn.net/u013286192/article/details/136418472Nginx配置详解https://www.runoob.com/w3cnote/nginx-setup-intro.html查看nginx开启......
  • JDK升级专题
    一、JVM17与JVM8的变化模块化系统(ProjectJigsaw)新的垃圾收集器  JDK17引入了ZGC和Shenandoah,这两个垃圾回收器在低延迟和高吞吐量方面表现优秀,同时提高了内存管理效率。 二、SpringBoot与SpringCloud版本对应关系及SpringBoot与JDK对应关系。   参考资料......
  • springBoot源码(一)
    构造函数运行代码publicConfigurableApplicationContextrun(String...args){ Startupstartup=Startup.create(); if(this.registerShutdownHook){ SpringApplication.shutdownHook.enableShutdownHookAddition(); } DefaultBootstrapContextbootstrapConte......
  • [ARC176E] Max Vector
    MyBlogs[ARC176E]MaxVector\(n=10\)其实有点误导性。其实这个题不是指数级的算法,而且贪心也不是很合理,同时“要么...要么...”有点像最小割。一次操作可以看成要求\(x_j\geqa_{i,j}\)或者\(y_j\geqa_{i,j}\)。考虑切糕的模型,建\(2n\)条链,割哪条边就表示第\(i\)个......
  • JDK源码分析-LinkedList
    概述相较于ArrayList,LinkedList在平时使用少一些。LinkedList内部是一个双向链表,并且实现了List接口和Deque接口,因此它也具有List的操作以及双端队列和栈的性质。双向链表的结构如下:它除了作为List使用,还可以作为队列或者栈来使用。publicclassLinkedList<E>......
  • Java源码阅读-String中的private final char value[];
    /**Thevalueisusedforcharacterstorage.*/privatefinalcharvalue[];在Java的源码中是这样来实现String对字符串的存储的首先使用final关键字来修饰这个变量,来保证value不会被重写,确保字符串的内容在创建后不会被修改,从而保持字符串的不可变性。final是......
  • Java源码阅读-String.startsWith(String prefix, int toffset)
    /***Testsifthesubstringofthisstringbeginningatthe*specifiedindexstartswiththespecifiedprefix.**@paramprefixtheprefix.*@paramtoffsetwheretobeginlookinginthisstring.*@return{@codetrue}ifthecharacter......
  • JDK源码分析-ArrayList
    概述ArrayList是List接口的一个实现类,也是Java中最常用的容器实现类之一,可以把它理解为「可变数组」。Java中的数组初始化时需要指定长度,而且指定后不能改变。ArrayList内部也是一个数组,它对数组的功能做了增强:主要是在容器内元素增加时可以动态扩容,这也是ArrayList的......
  • lodash已死?radash最全使用介绍(附源码说明)—— Array方法篇(4)
    写在前面tips:点赞+收藏=学会!我们已经介绍了radash的相关信息和部分Array相关方法,详情可前往主页查看。本篇我们继续介绍radash中Array的相关方法的剩余方法。本期文章发布后,作者也会同步整理出Array方法的使用目录,包括文章说明和脑图说明。因为方法较多,后续将专门发布......
  • 25-Mybatis源码分析
    1.架构设计&测试代码1.1Mybatis四层架构【API接口层】提供API增加、删除、修改、查询等接口,通过API接口对数据库进行操作;【数据处理层】主要负责SQL的查询、解析、执行以及结果映射的处理,主要作用解析SQL根据调用请求完成一次数据库操作;【框架支撑层】负责通用基......