SoFunction
Updated on 2025-03-08

The difference between ArrayList and Vector in Java

In Java,ArrayListandVectorare two commonly used dynamic array implementation classes. Although they all come trueListInterfaces and have many similarities in functions, but there are significant differences in some aspects, including thread safety, performance, synchronization mechanism, etc.

1. Introduction to ArrayList

ArrayListIt is one of the most commonly used classes in the Java collection framework. It is a dynamically resized array implementation where the elements stored can be quickly accessed through indexes.ArrayListNot guaranteed thread safety and is suitable for use in single-threaded environments. Its underlying structure is implemented based on arrays. When new elements need to be added, the capacity of the array will automatically expand as needed.

The main features of ArrayList:

  • Dynamic expansionArrayListThe capacity of  will automatically expand with the number of added elements. The default initial capacity is 10. When the capacity exceeds,ArrayListA new, larger capacity array will be created and the data in the original array will be copied over.
  • Non-thread safeArrayListNot thread-safe, multiple threads access and modify the same one at the same time.ArrayListInstances may result in inconsistent behavior. therefore,ArrayListSuitable for use in single-threaded or multi-threaded environments with external synchronization measures.
  • Efficient random access:becauseArrayListIt is implemented based on an array, and any element can be accessed directly through the index, with the time complexity of O(1), that is, the performance of random access is very high.

2. Vector Introduction

Vectoris another dynamic array implementation in Java, andArrayListSimilarly, it can also store a dynamic number of elements, and the capacity will automatically expand as needed. However,VectorIt is an early design class, belonging toPart of the package. andArrayListThe biggest difference isVectoris thread-safe, which makes it suitable for multi-threaded environments.

Key Features of Vector:

  • Thread safetyVectorAll methods are synchronized, soVectorIt is thread-safe. Multiple threads can access and modify the same one at the same time.Vectorinstance, without causing data inconsistency. It passes internallysynchronizedKeyword synchronization mechanism.
  • Capacity Management:andArrayListSimilar,VectorIt also automatically expands when the capacity exceeds. By default,VectorThe expansion strategy is to double the current capacity. However, developers can also specify an increment capacity through the constructor to control the way capacity growth.
  • Relatively low performance: Since each method is synchronized,VectorPerformance ratioArrayListIt is slower, especially in a single-threaded environment, thread-safe mechanisms will bring unnecessary overhead.

3. The main differences between ArrayList and Vector

1. Thread safety

ArrayList
ArrayListIt is non-thread-safe. If used in a multi-threaded environmentArrayList, requires manual synchronization, such as using(new ArrayList<>())To ensure thread safety. Usually, if used only in a single threaded environment,ArrayListis a better choice because it avoids unnecessary synchronization overhead.

Vector
VectorIt is thread-safe, and it ensures security in a multi-threaded environment by synchronizing all methods. Even if multiple threads are at the same timeVectorWhen doing the operation, the consistency of the data can also be guaranteed. However, frequent synchronization operations will bring performance overhead, soVectorThe efficiency is not as good as in a single threaded environmentArrayList

2. Capacity expansion mechanism

ArrayList
ArrayListThe capacity expansion strategy is to increase the current capacity by 50% when the array capacity is insufficient. For example, when the capacity is 10, if the 11th element is inserted,ArrayListThe capacity will be expanded to 15 (10 * 1.5).ArrayListThis growth method is relatively flexible and reduces unnecessary memory overhead.

Vector
VectorThe default capacity expansion strategy is to directly double the current capacity when the capacity is insufficient. also,VectorA construction method is also provided that allows developers to specify capacity increment. If the expansion amount is specified and the capacity is insufficient,VectorIt will increase by the specified expansion amount instead of directly doubling. A strategy of double expansion can sometimes lead to memory waste, especially in scenarios where capacity adjustments are required.

3. Performance differences

ArrayList
becauseArrayListWithout thread synchronization mechanism, its performance is more thanVectorhigh. In single-threaded environments or in situations where thread safety is not required,ArrayListIt is a better choice. Especially in high frequency read and write operations,ArrayListhas obvious performance advantages.

Vector
VectorThe synchronization mechanism results in better security in multi-threaded environments, but also reduces performance. In a multi-threaded environment, althoughVectorIt can ensure thread safety, but if the amount of access and operation is very large, frequent synchronous operations may lead to performance bottlenecks. Therefore, unless there is a clear multi-threading requirement, it is generally recommended to useArrayList

4. Traversal method

ArrayListandVectorAll support itIteratorandListIteratorPerform traversal. However, becauseVectorIt is synchronous and may encounter it during traversal.ConcurrentModificationException, that is, if another thread is modified during the traversal processVector, an exception will be thrown.

ForArrayListandVector, it is recommended to usefor-each loop or IteratorCome to traverse, not traditionalforLoop to avoid errors that may occur when dynamically expanding.

5. Abandonment and Substitution

AlthoughVectorIt can still be used, but it belongs to the collection class designed in the early days. Later, with the development of the Java collection framework,ArrayListIt has gradually become a more commonly used choice. Especially after Java 1.2 introduced the collection framework,ArrayListIt has become the first choice for dynamic arrays. andVectorIn order to ensure thread safety, developers can use external synchronization mechanism to deal withArrayListProcessing without usingVector

4. Choose ArrayList or Vector?

Based on the above analysis, the following basis for selection can be summarized:

  • Thread safety: If thread-safe dynamic array is needed,VectorIt is a ready-made solution. But in modern development, it is usually more inclined to useArrayListCooperate with external synchronization mechanisms (such asOr useCopyOnWriteArrayList)。
  • Performance requirements: Without multi-threaded safety requirements,ArrayListThe performance is far better thanVector, especially in scenarios where a large number of random access, insertion, deletion and other operations are performed.
  • Scaling strategy: If the application scenario requires frequent dynamic expansion and memory sensitive,ArrayListThe expansion method is more reasonable. It can effectively save memory by increasing capacity by 50%. andVectorThe strategy of double expansion may lead to more memory waste.

V. Sample code

The following are used separatelyArrayListandVectorExamples of adding, deleting and searching operations:

ArrayList Example:

import ;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        ("Apple");
        ("Banana");
        ("Cherry");
        
        ("ArrayList Elements:");
        for (String fruit : arrayList) {
            (fruit);
        }
    }
}

Vector Example:

import ;

public class VectorExample {
    public static void main(String[] args) {
        Vector<String> vector = new Vector<>();
        ("Apple");
        ("Banana");
        ("Cherry");
        
        ("Vector Elements:");
        for (String fruit : vector) {
            (fruit);
        }
    }
}

6. Summary

ArrayListandVectorThey are all very important dynamic array implementations in Java, but due to differences in thread safety, capacity expansion mechanism and performance,ArrayListMore suitable for single-threaded environments or scenarios with high performance requirements, andVectorIt is suitable for use in scenarios with multi-thread safety requirements. With the development of the Java collection framework,VectorThe use of   is gradually decreasing, and developers usually chooseArrayListCooperate with external synchronization mechanism to meet the needs of different scenarios.

This is the end of this article about the difference between ArrayList and Vector in Java. For more related Java ArrayList and Vector content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!