Environment to prepare

  • Java8_221 version
  • The Idea of the Debug configuration

Introduction to Vector

  1. AbstractList;
  2. The bottom layer is also an array of objects;
  3. Is thread-synchronized, that is, thread-safe. Vector operates with synchronized;
  4. During development, when you need a thread-synchronized safe collection, consider using a Vector;

Compare Vector with ArrayList

The underlying structure version Thread safety The efficiency of Expansion ratio
ArrayList An array variable jdk1.2 unsafe high If there is a parameter structure 1.5 times;

If there is no parameter:

1. First time 10

2. 1.5 times from the second time
Vector An array variable jdk1.0 security general If no parameter is set, the default value is 10. Expand the capacity by twice the original capacity.

If yes, each capacity expansion is twice the original capacity.

Read the source code

Source program

@SuppressWarnings(value = "all")
public class VectorSource {
  public static void main(String[] args) {
    Vector vector = new Vector();
    for (int i = 0; i < 10; i++) {
      vector.add(i);
    }
    vector.add(100); }}Copy the code

Read the source code

1. Add breakpoint, Debug run, and F7 Step Into

2. Set the size of the array to 10

2.1. Further down, you can see how to initialize

3. Add data. After initialization, it has 10 element capacity

4. Breakpoint switch to vector.add(100);

  • Determine whether capacity expansion is required
  • Reload data

5. Determine the minimum capacity and whether to expand the capacity. There’s no more minimum capacity here!

6. Expand the capacity. NewCapacity is twice the original capacity

CapacityIncrement = 0; capacityIncrement = 0; CapacityIncrement: oldCapacity) = oldCapacity. So oldCapacity + oldCapacity = oldCapacity*2

7. Add 10 elements

Grow () expansion function details

JDK 1.8.0_221 source code snippet

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);
}
Copy the code
  1. Elementdata. length is logged to oldCapacity with the first value of 0;
  2. newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); Expand the array by two times the current array capacity plus the current array capacity.
  3. The arrays.copyof () method can retain the original data for expansion;
  4. If the capacity exceeds2147483639The callhugeCapacityComputing capacity;