ArrayList Vector

1.ArrayList与Vector底层实现都是基于数组.

 

2.ArrayList与Vector初始化分配的空间都是10.

 

       public ArrayList() {
           this(10);
       }

 

       public Vector() {
           this(10);
       }

 

3. ArrayList底层实现中加入如下代码:

 

 private transient E[] elementData;

 

transient 关键字 在一个特定对象的一个域上关闭serialization,保证系统序列化是不会直接序列化elementData数组,而是通过writeObject和readObject实现序列化.

 

所以从序列化的角度看 ArrayList比Vector更安全.

 

4.Vector是线程安全的,因为Vector底层实现加入了synchronized关键字,而ArrayList不是

 

5.ArrayList每次扩展为自身容量的1.5倍.

public void ensureCapacity(int minCapacity) {
 modCount++;
 int oldCapacity = elementData.length;
 if (minCapacity > oldCapacity) {
     Object oldData[] = elementData;
     int newCapacity = (oldCapacity * 3)/2 + 1;

         if (newCapacity < minCapacity)
  newCapacity = minCapacity;
     elementData = (E[])new Object[newCapacity];
     System.arraycopy(oldData, 0, elementData, 0, size);
 }
    }

 

 

6.Vector根据capacityIncrement 的不同而不同,如果capacityIncrement >0 大小变为oldCapacity + capacityIncrement

如果capacityIncrement <0 大小变为原来的2倍

protected int capacityIncrement;

 

public Vector(int initialCapacity, int capacityIncrement) {
 super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
 this.elementData = new Object[initialCapacity];
 this.capacityIncrement = capacityIncrement;
    }

 

private void ensureCapacityHelper(int minCapacity) {
 int oldCapacity = elementData.length;
 if (minCapacity > oldCapacity) {
     Object[] oldData = elementData;
     int newCapacity = (capacityIncrement > 0) ?
  (oldCapacity + capacityIncrement) : (oldCapacity * 2);

         if (newCapacity < minCapacity) {
  newCapacity = minCapacity;
     }
     elementData = new Object[newCapacity];
     System.arraycopy(oldData, 0, elementData, 0, elementCount);
 }
    }

阅读更多
个人分类: Java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭