Vector扩容机制源码分析

再来稍微聊一下Vector的特点。

继承树

Vector继承树如下图:
在这里插入图片描述

特点

(1)允许null值

(2)底层使用动态对象数组Object[] elementData

(3)默认初始容量是10,也可通过构造函数指定初始容量(实际分配值)

(4)线程安全,通过synchronized锁得以保证

(5)fail-fast机制

(6)扩容与capacityIncrement参数相关,若此参数大于0,则按该值扩增容量,否则,成倍扩增

(7)如果需要扩容,则先扩容,再插入元素。

扩容机制---源码分析

以addElement方法为例:

	/**
     * Adds the specified component to the end of this vector,
     * increasing its size by one. The capacity of this vector is
     * increased if its size becomes greater than its capacity.
     *
     * <p>This method is identical in functionality to the
     * {@link #add(Object) add(E)}
     * method (which is part of the {@link List} interface).
     *
     * @param   obj   the component to be added
     */
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }
    
	/**
     * 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);
    }

再看扩容方法的核心:

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

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //根据capacityIncrement参数值决定扩容容量:指定值扩容/成倍扩容
        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;
    }
关于Stack

Stack的继承树:
在这里插入图片描述
Stack继承了Vector,也是线程安全的,方法上使用了synchronized锁。正如它的名字,它是一种先进后出的栈结构。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中的vector是一种动态数组,它可以根据需要自动扩容。当vector中的元素数量超过当前容量时,vector会重新分配一块更大的内存空间,并将原有元素复制到新的内存空间中。vector扩容机制可以通过reserve()和capacity()函数来观察和控制。 以下是一个示例代码,演示了vector扩容机制: ```c++ #include <iostream> #include <vector> int main() { std::vector<int> vec; std::cout << "Initial capacity: " << vec.capacity() << std::endl; // 输出:Initial capacity: 0 for (int i = 0; i < 10; i++) { vec.push_back(i); std::cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << std::endl; } // 输出: // Size: 1, Capacity: 1 // Size: 2, Capacity: 2 // Size: 3, Capacity: 4 // Size: 4, Capacity: 4 // Size: 5, Capacity: 8 // Size: 6, Capacity: 8 // Size: 7, Capacity: 8 // Size: 8, Capacity: 8 // Size: 9, Capacity: 16 // Size: 10, Capacity: 16 vec.reserve(20); std::cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << std::endl; // 输出:Size: 10, Capacity: 20 return 0; } ``` 在上面的代码中,我们首先创建了一个空的vector,并输出了它的初始容量。然后我们通过push_back()函数向vector中添加元素,每次添加一个元素后,都输出当前vector的大小和容量。可以看到,当vector的大小超过当前容量时,vector会自动扩容,容量扩大的规则是:如果当前容量不足以容纳新元素,则将容量扩大为原来的两倍。最后,我们使用reserve()函数将vector的容量设置为20,并输出了当前vector的大小和容量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值