Collection Family List (three): Vector

Vector and implementation of the underlying structure and ArrayList identical, but may differ in certain details. These details are:

  • Thread Safety
  • Expansion size

Thread Safety

We know that ArrayList is not thread-safe, can only be used in single-threaded environment. The Vector is thread-safe, then how to actually achieve it?

Vector fact achieve is very simple, that is, in every possible thread-safe method of adding synchronized keyword. This makes any time only one thread can read and write, thus ensuring thread safety.

public synchronized E get(int index) {
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);

    return elementData(index);
}
public synchronized boolean add(E e) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = e;
    return true;
}

Expansion size

ArrayList and similar, Vector element during insertion and expansion capacity is also checked. In this method the Vector is: ensureCapacityHelper.

private void ensureCapacityHelper(int minCapacity) {
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                     capacityIncrement : oldCapacity);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    elementData = Arrays.copyOf(elementData, newCapacity);
}

In fact, the above-mentioned expansion of ideas and ArrayList is the same, the only difference is the size of the expansion of the Vector.

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

We can see from the above code: If capacityIncrement greater than 0, then in accordance with capacityIncrement to expansion, or expanded to 2 times the original. The ArrayList is expanded to 1.5 times.

to sum up

Vector and ArrayList in the implementation is exactly the same, but they are slightly different in some methods:

  • First, Vector is thread-safe, but ArrayList is thread safe. Vector keywords directly synchronize synchronization.
  • Second, Vector expansion to the original default is 2, and default ArrayList expansion of 1.5 times.

Guess you like

Origin www.cnblogs.com/chanshuyi/p/java_collection_03_vector.html