Vector源码

news2024/10/7 20:34:43

介绍

  • Vector是矢量队列,继承于AbstractList,实现了List, RandomAccess, Cloneable和Serializable接口
  • Vector继承了AbstractList,实现了List接口,所以它是一个队列,支持相关的添加、删除、修改、遍历等功能
  • Vector实现了RandomAccess接口,即提供了随机访问功能。在Vector中,我们可以通过元素的序号快速获取元素对象,这就是快速随机访问。
  • Vector实现了Cloneable接口,即实现了clone()方法,可以被克隆
  • 和ArrayList不同,Vector中的操作是线程安全的
public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

image-20230604114538478

常量&变量

    /**
     * The array buffer into which the components of the vector are
     * stored. The capacity of the vector is the length of this array buffer,
     * and is at least large enough to contain all the vector's elements.
     *
     * <p>Any array elements following the last element in the Vector are null.
     *
     * @serial
     * 数组缓冲区
     */
    protected Object[] elementData;

    /**
     * The number of valid components in this {@code Vector} object.
     * Components {@code elementData[0]} through
     * {@code elementData[elementCount-1]} are the actual items.
     *
     * @serial
     * 元素个数
     */
    protected int elementCount;

    /**
     * The amount by which the capacity of the vector is automatically
     * incremented when its size becomes greater than its capacity.  If
     * the capacity increment is less than or equal to zero, the capacity
     * of the vector is doubled each time it needs to grow.
     *
     * @serial
     * 容量增量 如果容量增量小于或等于零,则每次需要增长时,向量的容量将增加一倍。
     */
    protected int capacityIncrement;

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    //序列化版本号
    private static final long serialVersionUID = -2767605614048989439L;

    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     * 存储元素最大值
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

构造方法

    /**
     * The amount by which the capacity of the vector is automatically
     * incremented when its size becomes greater than its capacity.  If
     * the capacity increment is less than or equal to zero, the capacity
     * of the vector is doubled each time it needs to grow.
     *
     * @serial
     * 容量增量 如果容量增量小于或等于零,则每次需要增长时,向量的容量将增加一倍。
     */
    protected int capacityIncrement;

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    //序列化版本号
    private static final long serialVersionUID = -2767605614048989439L;

    /**
     * Constructs an empty vector with the specified initial capacity and
     * capacity increment.
     *
     * @param   initialCapacity     the initial capacity of the vector
     * @param   capacityIncrement   the amount by which the capacity is
     *                              increased when the vector overflows
     * @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;
    }

    /**
     * Constructs an empty vector with the specified initial capacity and
     * with its capacity increment equal to zero.
     *
     * @param   initialCapacity   the initial capacity of the vector
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     *         构造具有指定初始容量并且其容量增量等于零的空向量。
     */
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    /**
     * Constructs an empty vector so that its internal data array
     * has size {@code 10} and its standard capacity increment is
     * zero.
     * 构造一个空向量,使其内部数据数组的大小为 10 ,标准容量增量为零。
     */
    public Vector() {
        this(10);
    }

    /**
     * Constructs a vector containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this
     *       vector
     * @throws NullPointerException if the specified collection is null
     * @since   1.2
     * 构造一个包含指定集合元素的向量,按照集合的迭代器返回的顺序。
     */
    public Vector(Collection<? extends E> c) {
        Object[] a = c.toArray();
        elementCount = a.length;
        //c为ArrayList类型 直接赋值
        if (c.getClass() == ArrayList.class) {
            elementData = a;
        } else {
            //拷贝
            elementData = Arrays.copyOf(a, elementCount, Object[].class);
        }
    }

内部类

参考ArrayList源码

添加

add(E e)

将元素插入到Vector末尾

    /**
     * Appends the specified element to the end of this Vector.
     *
     * @param e element to be appended to this Vector
     * @return {@code true} (as specified by {@link Collection#add})
     * @since 1.2
     */
    public synchronized boolean add(E e) {
        modCount++;
        // 确定插入后的容量没有超过最大容量,否则对Vector进行扩容
        ensureCapacityHelper(elementCount + 1);
        // 将e赋值给elementData[elementCount],然后将Vector元素数量加1
        elementData[elementCount++] = e;
        return true;
    }

add(int index, E element)

将元素插入到指定的index处

    /**
     * Inserts the specified element at the specified position in this Vector.
     * Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @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方法
        insertElementAt(element, index);
    }

insertElementAt(E obj, int index)

    /**
     * Inserts the specified object as a component in this vector at the
     * specified {@code index}. Each component in this vector with
     * an index greater or equal to the specified {@code index} is
     * shifted upward to have an index one greater than the value it had
     * previously.
     *
     * <p>The index must be a value greater than or equal to {@code 0}
     * and less than or equal to the current size of the vector. (If the
     * index is equal to the current size of the vector, the new element
     * is appended to the Vector.)
     *
     * <p>This method is identical in functionality to the
     * {@link #add(int, Object) add(int, E)}
     * method (which is part of the {@link List} interface).  Note that the
     * {@code add} method reverses the order of the parameters, to more closely
     * match array usage.
     *
     * @param      obj     the component to insert
     * @param      index   where to insert the new component
     * @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);
        }
        // 确定插入后的容量没有超过最大容量,否则对Vector进行扩容
        ensureCapacityHelper(elementCount + 1);
        // 使用System.arraycopy将elementData[index]及其之后的元素向后移动一个位置
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
        // 将obj赋值给elementData[index]
        elementData[index] = obj;
        // Vector元素数量加1
        elementCount++;
    }

删除

remove(int index)

删除指定index上的元素

    /**
     * Removes the element at the specified position in this Vector.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).  Returns the element that was removed from the Vector.
     *
     * @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);
        // 获取index处原先的值
        E oldValue = elementData(index);

        int numMoved = elementCount - index - 1;
        if (numMoved > 0)
            // 使用System.arraycopy将elementData[index]之后的元素向前移动一个位置
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        // 将Vector最后一个元素设置为null(以便进行gc),然后将Vector元素数量减1
        elementData[--elementCount] = null; // Let gc do its work
        // 返回index处原先的值
        return oldValue;
    }

remove(Object o)

删除特定元素o

    /**
     * Removes the first occurrence of the specified element in this Vector
     * If the Vector does not contain the element, it is unchanged.  More
     * formally, removes the element with the lowest index i such that
     * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
     * an element exists).
     *
     * @param o element to be removed from this Vector, if present
     * @return true if the Vector contained the specified element
     * @since 1.2
     */
    public boolean remove(Object o) {
        // 直接调用removeElement方法
        return removeElement(o);
    }

removeElement

    /**
     * Removes the first (lowest-indexed) occurrence of the argument
     * from this vector. If the object is found in this vector, each
     * component in the vector with an index greater or equal to the
     * object's index is shifted downward to have an index one smaller
     * than the value it had previously.
     *
     * <p>This method is identical in functionality to the
     * {@link #remove(Object)} method (which is part of the
     * {@link List} interface).
     *
     * @param   obj   the component to be removed
     * @return  {@code true} if the argument was a component of this
     *          vector; {@code false} otherwise.
     */
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        // 获取元素obj的索引
        // 根据indexOf的源码,若Vector中存在多个obj,将返回遍历Vector得到的第一个obj的索引
        int i = indexOf(obj);
        // 若元素obj存在
        if (i >= 0) {
            // 调用removeElementAt删除指定索引的元素
            // removeElementAt方法与上面的remove(int index)方法基本一致
            removeElementAt(i);
            return true;
        }
        return false;
    }

查找

get(int index)

获取指定index处的元素

    /**
     * Returns the element at the specified position in this Vector.
     *
     * @param index index of the element to return
     * @return object at the specified 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);
        // 直接调用elementData方法
        return elementData(index);
    }

修改

set(int index, E element)

修改index处的元素

    /**
     * Replaces the element at the specified position in this Vector with the
     * specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @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);
        // 获取index处原先的值
        E oldValue = elementData(index);
        // 将element赋值给elementData[index]
        elementData[index] = element;
        // 返回index处原先的值
        return oldValue;
    }

扩容

ensureCapacityHelper(int minCapacity)

确保容量

    /**
     * This implements the unsynchronized semantics of ensureCapacity.
     * Synchronized methods in this class can internally call this
     * method for ensuring capacity without incurring the cost of an
     * extra synchronization.
     *
     * @see #ensureCapacity(int)
     */
    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);
        // 使用Arrays.copyOf方法将原数组元素复制到容量为newCapacity的新数组中
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/621868.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

chatgpt赋能python:Python的强制语句缩进解析

Python的强制语句缩进解析 什么是语句缩进 在其他编程语言中&#xff0c;我们通过使用花括号或者一些其他的符号来区分控制语句的范围。但在Python中&#xff0c;我们使用缩进来实现这个目的。这意味着任何控制结构的主体都必须按照要求正确缩进。 为什么Python强制要求使用…

【Java】JavaWEB核心要点总结:63

文章目录 1. JSP 和 Servlet 有什么区别2. JSP有哪些内置对象 分别是什么3. 详细讲解cookie session token4. 如果客户端禁止 了cookie &#xff0c;session 还能用吗5. session 的工作原理 1. JSP 和 Servlet 有什么区别 JSP&#xff08;Java Server Pages&#xff09;和Servl…

读改变未来的九大算法笔记06_图形识别

1. 人工智能研究人员在过去几十年中学到的最重要的教训之一 1.1. 看似智能的行为有可能从看似随机的系统中浮现出来 1.2. 如果我们有能力进入人脑&#xff0c;研究神经元之间连接的强度&#xff0c;其中绝大部分连接都会表现得很随机 1.3. 当作为集合体行动时&#xff0c;这…

javaScript蓝桥杯-----全球新冠疫情数据统计

目录 一、介绍二、准备三、⽬标四、代码五、完成 一、介绍 新冠疫情席卷全球&#xff0c;在此期间有很多免费的 API 和⽹站为⼈们提供了各个国家疫情数据的查询功能&#xff0c;这些免费公开的数据体现出了互联⽹作为信息媒介的优越性&#xff0c;帮助全球⼈⺠更好的了解⼀线疫…

电路模型和电路定律(3)——“电路分析”

小雅兰期末加油冲冲冲&#xff01;&#xff01;&#xff01; 复习之前的内容&#xff1a; 这样的连接方式是不可以的&#xff1a; 两个电压源&#xff0c;电压值不相同&#xff0c;是不能并联的 两个电流源&#xff0c;电流值不相同&#xff0c;是不能串联的 电流源也不能开…

浅谈Zuul、Gateway

一、Zuul Zuul是通过Servlet来实现的&#xff0c;Zuul通过自定义的ZuulServlet&#xff08;类似于Spring MVC的DispatcherServlet&#xff09;来对请求进行控制(一系列过滤器处理Http请求)。 所有的Request都要经过ZuulServlet的处理&#xff0c;三个核心的方法preRoute(),rou…

时钟频率的配置-DG32

时钟频率的配置-DG32 HXTAL&#xff1a;高速外部时钟&#xff0c;4到32MHz的外部振荡器&#xff0c;可为系统提供精确的主时钟。带有特定频率的晶体必须靠近两个HXTAL的引脚。和晶体连接的外部电阻和电容必须根据所选择的振荡器来调整&#xff1b; LXTAL&#xff1a;低速外部…

chatgpt赋能python:Python开发桌面应用全面介绍

Python开发桌面应用全面介绍 Python是一种非常万能的编程语言&#xff0c;也逐步发展成为一种适用于开发各种桌面应用程序的语言。Python开发桌面应用的优点是它可以快速开发&#xff0c;易于阅读和使用&#xff0c;同时具有很高的可扩展性和可维护性&#xff0c;因此越来越多…

chatgpt赋能python:Python开立方:简单快捷的计算方法

Python开立方&#xff1a;简单快捷的计算方法 如果你是一位程序员或者是一个正在学习编程的初学者&#xff0c;那么你一定会用到Python这个编程语言。Python作为一门多用途的编程语言&#xff0c;它有着简单易学、高效快捷、优雅简洁等优点。同时&#xff0c;在数据分析、人工…

Keras-3-实例2-多分类问题

1. 多分类问题&#xff1a; 1.1 路透社数据集加载 路透社数据集由路透社在1986年发布&#xff0c;包含46个不同的主题&#xff1a;某些主题样本较多&#xff0c;某些较少&#xff0c;但是训练集中每个主题都至少含有10个样本。 from keras.datasets import reuters(train_da…

ViewOverlay-加蒙层真的一种实现方式

一、ViewOverlay能实现什么&#xff1f; 在Android中&#xff0c;ViewOverlay是一个特殊的视图层&#xff0c;可以在一个视图的上方添加和管理附加的视图层&#xff0c;而不会干扰原始视图的布局和交互。它提供了一种方便的方式来在运行时添加、移除或修改视图层&#xff0c;而…

chatgpt赋能python:Python嵌入SEO

Python嵌入SEO Python是一种高级编程语言&#xff0c;由于其简单易学和广泛应用的特点&#xff0c;已经成为了许多工程师的首选语言。随着互联网发展的趋势&#xff0c;现代的SEO已经不再是简单的关键词填充和链接堆积&#xff0c;而是需要更复杂的优化方式&#xff0c;这时候…

Sentinel在k8s部署

一、Sentinel Dashboard在k8s部署 官方jar包下载 由于sentinel dashboard官方没有提供镜像下载&#xff0c;需从sentinel官方下载sentinel dashboard的jar包&#xff0c;这里选择1.8.0进行下载。注意与springboot版本的兼容性。 打镜像并上传自己镜像仓库 在自己项目中添加…

mac(M1)芯片安装Stable-diffusion-webui

背景&#xff1a;听同事说这个都是在GPU上跑的&#xff0c;cpu跑这个比较费劲。我本地mac跑这个&#xff0c;也是为了调试一些相关的插件和api。为了开发方便点。当然确实提吃内存的。 目录 一、Stable-diffusion-webui 项目地址和官方安装方式 二、自己的安装方式 2.1、更…

自定义注解,基于redis实现分布式锁

一、如何实现自定义注解 1.1、注解的基础知识 实现自定义注解其实很简单&#xff0c;格式基本都差不多。也就参数可能变一变。 Retention&#xff1a;取值决定了注解在什么时候生效&#xff0c;一般都是取运行时&#xff0c;也就是RetentionPolicy.RUNTIME。 Target&#xff…

Unreal5 第三人称射击游戏 射击功能实现2

上一篇我们实现了角色射击相关的动画以及切换逻辑&#xff0c;并将武器相关的模型添加到角色身上。 这一篇开始制作武器相关的功能。 制作子弹父类 首先创建一个actor类&#xff0c;命名为BP_Bullet&#xff0c;这个作为子弹的通用父类&#xff0c;在里面创建子弹通用的功能实…

测试相关知识

测试基础知识 1. 测试基本理念2. 软件测试的分类2.1 程序是否运行2.2 测试时间段划分2.3 是否涉及实现2.4 其它测试2.5 当前流程的测试概念 3. 测试设计方法4. 参考书籍 1. 测试基本理念 软件测试的定义&#xff1a;软件测试是使用人工或自动的手段来运行或测定某个软件系统的…

chatgpt赋能python:Python年龄换算:如何根据Python版本算出“年龄”?

Python年龄换算&#xff1a;如何根据Python版本算出“年龄”&#xff1f; Python是一种高级编程语言&#xff0c;享有强大、易读、易用和可扩展性等各种优点。它是许多开发者使用的首选语言&#xff0c;尤其在数据科学和机器学习领域中备受推崇。 但是&#xff0c;Python几乎…

网络安全工具合集

首先&#xff0c;恭喜你发现了宝藏。 本文章集成了全网优秀的开源攻防武器项目&#xff0c;包含&#xff1a; 信息收集工具&#xff08;自动化利用工具、资产发现工具、目录扫描工具、子域名收集工具、指纹识别工具、端口扫描工具、各种插件....etc...&#xff09; 漏洞利用…

轮廓检测及功能

目录 一、实验介绍二、实验步骤三、实验任务任务一&#xff1a;轮廓特征练习一: 找到每个轮廓的方向任务二&#xff1a;边界矩形练习二: 围绕轮廓裁剪图像 一、实验介绍 1. 实验内容 本实验将学习轮廓检测及功能。 2. 实验要点 生成二进制图像来查找轮廓找到并画出轮廓轮廓…