In Java,ArrayList
andVector
are two commonly used dynamic array implementation classes. Although they all come trueList
Interfaces 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
ArrayList
It 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.ArrayList
Not 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 expansion:
ArrayList
The capacity of will automatically expand with the number of added elements. The default initial capacity is 10. When the capacity exceeds,ArrayList
A new, larger capacity array will be created and the data in the original array will be copied over. -
Non-thread safe:
ArrayList
Not thread-safe, multiple threads access and modify the same one at the same time.ArrayList
Instances may result in inconsistent behavior. therefore,ArrayList
Suitable for use in single-threaded or multi-threaded environments with external synchronization measures. -
Efficient random access:because
ArrayList
It 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
Vector
is another dynamic array implementation in Java, andArrayList
Similarly, it can also store a dynamic number of elements, and the capacity will automatically expand as needed. However,Vector
It is an early design class, belonging toPart of the package. and
ArrayList
The biggest difference isVector
is thread-safe, which makes it suitable for multi-threaded environments.
Key Features of Vector:
-
Thread safety:
Vector
All methods are synchronized, soVector
It is thread-safe. Multiple threads can access and modify the same one at the same time.Vector
instance, without causing data inconsistency. It passes internallysynchronized
Keyword synchronization mechanism. -
Capacity Management:and
ArrayList
Similar,Vector
It also automatically expands when the capacity exceeds. By default,Vector
The 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,
Vector
Performance ratioArrayList
It 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:ArrayList
It 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,ArrayList
is a better choice because it avoids unnecessary synchronization overhead.
Vector:Vector
It is thread-safe, and it ensures security in a multi-threaded environment by synchronizing all methods. Even if multiple threads are at the same timeVector
When doing the operation, the consistency of the data can also be guaranteed. However, frequent synchronization operations will bring performance overhead, soVector
The efficiency is not as good as in a single threaded environmentArrayList
。
2. Capacity expansion mechanism
ArrayList:ArrayList
The 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,ArrayList
The capacity will be expanded to 15 (10 * 1.5).ArrayList
This growth method is relatively flexible and reduces unnecessary memory overhead.
Vector:Vector
The default capacity expansion strategy is to directly double the current capacity when the capacity is insufficient. also,Vector
A construction method is also provided that allows developers to specify capacity increment. If the expansion amount is specified and the capacity is insufficient,Vector
It 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:
becauseArrayList
Without thread synchronization mechanism, its performance is more thanVector
high. In single-threaded environments or in situations where thread safety is not required,ArrayList
It is a better choice. Especially in high frequency read and write operations,ArrayList
has obvious performance advantages.
Vector:Vector
The synchronization mechanism results in better security in multi-threaded environments, but also reduces performance. In a multi-threaded environment, althoughVector
It 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 itIterator
andListIterator
Perform traversal. However, becauseVector
It 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.
ForArrayList
andVector
, it is recommended to usefor-each
loop or Iterator
Come to traverse, not traditionalfor
Loop to avoid errors that may occur when dynamically expanding.
5. Abandonment and Substitution
AlthoughVector
It 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,ArrayList
It has gradually become a more commonly used choice. Especially after Java 1.2 introduced the collection framework,ArrayList
It has become the first choice for dynamic arrays. andVector
In order to ensure thread safety, developers can use external synchronization mechanism to deal withArrayList
Processing 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,
Vector
It is a ready-made solution. But in modern development, it is usually more inclined to useArrayList
Cooperate with external synchronization mechanisms (such asOr use
CopyOnWriteArrayList
)。 -
Performance requirements: Without multi-threaded safety requirements,
ArrayList
The 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,
ArrayList
The expansion method is more reasonable. It can effectively save memory by increasing capacity by 50%. andVector
The strategy of double expansion may lead to more memory waste.
V. Sample code
The following are used separatelyArrayList
andVector
Examples 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
ArrayList
andVector
They are all very important dynamic array implementations in Java, but due to differences in thread safety, capacity expansion mechanism and performance,ArrayList
More suitable for single-threaded environments or scenarios with high performance requirements, andVector
It is suitable for use in scenarios with multi-thread safety requirements. With the development of the Java collection framework,Vector
The use of is gradually decreasing, and developers usually chooseArrayList
Cooperate 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!