侧边栏壁纸
博主头像
晓果冻博主等级

一个热爱生活的95后精神小伙

  • 累计撰写 123 篇文章
  • 累计创建 14 个标签
  • 累计收到 56 条评论

目 录CONTENT

文章目录

ArrayList和Vector异同点

晓果冻
2021-07-30 / 0 评论 / 2 点赞 / 237 阅读 / 1,512 字
温馨提示:
本文最后更新于 2021-10-26,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

ArrayListVector异同点

相同点:

  • 底层都是数组

    //ArrayList
    transient Object[] elementData;
    
    //Vector
    protected Object[] elementData;
    
  • 默认大小都是10

    //Vector
    public Vector() {
        this(10);
    }
    //ArrayList
    private static final int DEFAULT_CAPACITY = 10;
    public ArrayList(int initialCapacity) {
            if (initialCapacity > 0) {
                this.elementData = new Object[initialCapacity];
            } else if (initialCapacity == 0) {
                this.elementData = EMPTY_ELEMENTDATA;
            } else {
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
            }
    }
    

不同点

  • 线程安全

    //ArrayList线程不安全,例如
    public boolean add(E e) {
            ensureCapacityInternal(size + 1);  // Increments modCount!!
            elementData[size++] = e;
            return true;
    }
    //Vector线程安全,例如,加了synchronized关键字
    public synchronized boolean add(E e) {
            modCount++;
            ensureCapacityHelper(elementCount + 1);
            elementData[elementCount++] = e;
            return true;
    }
    
  • 扩容倍数

    //ArrayList  1.5倍
    private void grow(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1);//1.5倍扩容
            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                newCapacity = hugeCapacity(minCapacity);
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
    }
    //Vector 2倍扩容
    private void grow(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                             capacityIncrement : oldCapacity);//2倍扩容
            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                newCapacity = hugeCapacity(minCapacity);
            elementData = Arrays.copyOf(elementData, newCapacity);
    }
    
2

评论区