2013-03-11 09:37:05.0|分类: java|浏览量: 1498
arraylist和vetor区别: (1)Vectors是可同步化的,意思就是说,任何操作Vector的内容的方法都是线程安全的,arrayList是不可同步化的,所以也不是线程安全的。 因为vectors是线程安全的,并且使用了关键字synchronized,这就是的vectors的性能不如arraylist的高,所以假如对想成安全要求不是很高的话,建议使用arraylist。 (2)ArrayList数据容器满后是按照原先容量的50%增加 Vector数据容器满后是按照原先容量的1倍增加,Vector还能还能自定义增加的容量,这个值是在构造vector函数中传入。 ArrayList类中的主要部分代码: package java.util; public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { public ArrayList() { this(10); } public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); ensureCapacity(size+1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } 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); } } }Vector类中部分代码: package java.util; public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { public Vector() { this(10); } public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; } 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); } } } |