(1)ArrayList是线程不安全的,效率高,而Vector是线程安全的,效率低。
ArrayList源码:
/**
* {@inheritDoc}
*/
public boolean equals(Object o) { //没有加synchronized
if (o == this) {
return true;
}
if (!(o instanceof List)) {
return false;
}
final int expectedModCount = modCount;
// ArrayList can be subclassed and given arbitrary behavior, but we can
// still deal with the common case where o is ArrayList precisely
boolean equal = (o.getClass() == ArrayList.class)
? equalsArrayList((ArrayList<?>) o)
: equalsRange((List<?>) o, 0, size);
checkForComodification(expectedModCount);
return equal;
}
Vector源码:
public synchronized boolean equals(Object o) { //都加了synchronized
return super.equals(o);
}
/**
* Returns the hash code value for this Vector.
*/
public synchronized int hashCode() {
return super.hashCode();
}
/**
* Returns a string representation of this Vector, containing
* the String representation of each element.
*/
public synchronized String toString() {
return super.toString();
}
(2)ArrayList在扩容的时候,扩容的是1.5倍,而Vector扩容的是2倍。
ArrayList源码:
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//右移相当于oldCapacity /2 两者相加相当于扩容1.5倍
右移相当于oldCapacity /2 两者相加相当于扩容1.5倍。
Vector源码:
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
一般capacityIncrement 不会赋值,所以oldCapacity+ oldCapacity相当于扩容2倍。