The difference between java ArrayList and Vector

  • 2020-05-12 02:44:50
  • OfStack

The difference between ArrayList and Vector

Similarities:

1. ArrayList and Vector both inherit from the same parent class and implement the same interface

2. The bottom layer is implemented by arrays

3. The initial default length is 10.

Difference:

1. Synchronicity:

Most public methods in Vector add the synchronized keyword to ensure method synchronization, that is, Vector thread safe, ArrayList thread unsafe.

2. Different capacity expansion

Internal attributes are different, which may be the reason for the different expansion mode.

ArrayList has two properties, elementData, an array that stores data, and size, which stores the number of records.

Vector has three properties: elementData, which stores the array of data, elementCount, which stores the number of records, and capacityIncrement, which extends the size of the array.

ArrayList extension method


//jdk1.8.0_91
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
      newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
      newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
  }

It can be seen that, when the expansion condition is met, the size of the expanded array is 1.5 times the length of the original array and the larger of the passed parameters

Vector extension method


//jdk1.8.0_91
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);
  }

It can be seen that when the expansion factor is greater than 0, the length of the new array is the length of the original array + the expansion factor; otherwise, the length of the sub-new array is twice the length of the original array. Compare the length of the new array generated above with the length of the passed parameter, with the larger being the final new length.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: