What are the differences between ArrayList and Vector?
两个数据结构ArrayList和Vector之间有什么区别,你应该在哪里使用它们?
Differences
Use ArrayLists if there is no specific requirement to use Vectors.
Synchronization
If multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which modifies the list either structurally or simply modifies an element. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.
Collections.synchronizedList
is normally used at the time of creation of the list to avoid any accidental unsynchronized access to the list.
Reference
Data growth
Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
Reference
As the documentation says, a Vector
and an ArrayList
are almost equivalent. The difference is that access to a Vector
is synchronized, whereas access to an ArrayList
is not. What this means is that only one thread can call methods on a Vector
at a time, and there's a slight overhead in acquiring the lock; if you use an ArrayList
, this isn't the case. Generally, you'll want to use an ArrayList
; in the single-threaded case it's a better choice, and in the multi-threaded case, you get better control over locking. Want to allow concurrent reads? Fine. Want to perform one synchronization for a batch of ten writes? Also fine. It does require a little more care on your end, but it's likely what you want. Also note that if you have an ArrayList, you can use the Collections.synchronizedList
function to create a synchronized list, thus getting you the equivalent of a Vector
.
Vector
is a broken class that is not threadsafe, despite it being "synchronized" and is only used by students and other inexperienced programmers.
ArrayList
is the go-to List implementation used by professionals and experienced programmers.
Professionals wanting a threadsafe List implementation use a CopyOnWriteArrayList
.