前面讨论过ArrayList与LinkedList的区别,ArrayList的底层数据结构是数组Object[],而LinkedList底层维护

的是一个链表Entry,所以对于查询,肯定是ArrayList的效率高,但是对于删除和插入则是LinedList效率高。

现在我们再来看看Vector与ArrayList的区别,直接上源码,ArrayList源码:

1:扩容方面,ArrayList扩容扩原来容量的3/2+1,而Vector扩容为原来容量的2倍

 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;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}

2:Vector源码

  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 = Arrays.copyOf(elementData, newCapacity);
}
}

默认创建的Vector对象new Vector(); 默认

capacityIncrement = 0
  public Vector() {
this(10);
}

调一个参数的构造方法:

  public Vector(int initialCapacity) {
this(initialCapacity, 0);
}

默认增长容量为0

调用两个参数的构造方法:

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

所以

 int newCapacity = (capacityIncrement > 0) ?
(oldCapacity + capacityIncrement) : (oldCapacity * 2);

新的容量扩展到原来的2倍。

再来看它们的另外一个区别,ArrayList类中的方法都是没有synchronized修饰的,所以都是非线程安全的,

获取集合中元素数量:

  public int size() {
return size;
}

判断集合是否为空:

  public boolean isEmpty() {
return size == 0;
}
   public boolean contains(Object o) {
return indexOf(o) >= 0;
}

。。。。。

再来看看Vector类,方法都是由synchronized修饰,所以是线程安全的,万事都是有利有弊,线程安全的处理数据效率会低,而线程非安全的处理

数据效率相对高一些:

 public synchronized void setSize(int newSize) {
modCount++;
if (newSize > elementCount) {
ensureCapacityHelper(newSize);
} else {
for (int i = newSize ; i < elementCount ; i++) {
elementData[i] = null;
}
}
elementCount = newSize;
}
 public synchronized int capacity() {
return elementData.length;
}
   public synchronized int size() {
return elementCount;
}
   public synchronized boolean isEmpty() {
return elementCount == 0;
}

。。。。。。

05-08 15:21