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

行动起来,活在当下

  • 累计撰写 135 篇文章
  • 累计创建 16 个标签
  • 累计收到 91 条评论

目 录CONTENT

文章目录

ArrayList和Vector异同点

Administrator
2021-07-30 / 0 评论 / 2 点赞 / 515 阅读 / 2377 字

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

评论区