zoukankan      html  css  js  c++  java
  • 集合框架系列(二)Vector源码分析

    目录

    1 概述

    2 源码分析

    1 概述

    Vector 的底层实现以及结构与 ArrayList 完全相同,只是在某一些细节上会有所不同。这些细节主要有:

    • 线程安全
    • 扩容大小

    2 源码分析

    2.1 线程安全

    我们知道 ArrayList 是线程不安全的,只能在单线程环境下使用。而 Vector 则是线程安全的,那么其实怎么实现的呢?

    其实 Vector 的实现很简单,就是在每一个可能发生线程安全的方法加上 synchronized 关键字。这样就使得任何时候只有一个线程能够进行读写,这样就保证了线程安全比如下面两个方法:

    public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
    
        return elementData(index);
    }
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

    2.2 扩容大小

    与 ArrayList 类似,Vector 在插入元素时也会检查容量并扩容。在 Vector 中这个方法是:ensureCapacityHelper。

    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }
    
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    
    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);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    其实上述扩容的思路与 ArrayList 是相同,唯一的区别是 Vector 的扩容大小。从上面的代码可以看到:如果 capacityIncrement 大于 0,那么就按照 capacityIncrement 去扩容,否则扩大为原来的 2倍。而 ArrayList 则是扩大为原来的 1.5 倍。对于 capacityIncrement 这个是ArrayList中没有的,根据注释可以知道这个变量就是自己定义每次扩容的大小。

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

    0

  • 相关阅读:
    Android中的网络编程
    JAVA 中的IO流
    JAVA网络编程
    JAVA中List的三个子类。
    JAVA中List的几个方法
    JAVA集合中的迭代器的遍历
    JAVA中集合转数组遍历
    【安卓4】事件处理——时间日期事件处理、长按事件
    【安卓4】事件处理——单选按钮触发事件、下拉列表触发事件
    【安卓4】事件处理——单击事件
  • 原文地址:https://www.cnblogs.com/youngao/p/12517672.html
Copyright © 2011-2022 走看看