Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList vs Vector : Which one to use?

At the very beginning, I'll admit it that I'm an idiot; but there's one thing that I just can't seem to understand. I can't seem to find much difference between ArrayList and Vector other than this:

"...(This class is roughly equivalent to Vector, except that it is unsynchronized.)... "

in the javaDocs of ArrayList.

So, is this difference really an important factor in the way we apply these two similar classes when we consider the general scenario (i.e. ruling out the application in Thread-based programming)? Are there any other marked differences? If so, please tell me. If not, then which one is the most preferred or generally accepted approach?

like image 326
Hungry Blue Dev Avatar asked Feb 27 '14 13:02

Hungry Blue Dev


2 Answers

According to Java API:

"it is recommended to use ArrayList in place of Vector"

Still you can get a synchronized version of a List with Collections:

Collections.synchronizedList(List<T> list)

for example

List list = Collections.synchronizedList(new ArrayList());

This returns a synchronized (thread-safe) list backed by the specified list.

like image 35
Boris Avatar answered Oct 13 '22 10:10

Boris


Other than differences with synchronization, there is also a difference internally when you insert new elements. For both classes, the array within must be increased in size to prevent it from running out of room. Vectors double their size by default. ArrayLists increase their size by half their present size.

Edit:

Also, a couple answers mentioned that Vectors are thread safe. That's true to some extent, but the whole reason they're sort-of-deprecated (I think) is because they're not very useful for most synchronization needs, which is because it synchronizes on every operation (not safe). What you want to do usually is synchronize on a sequence of operations. Vectors don't do that (neither do ArrayLists though) so it's not really the way to go even in situations that require synchronization (basically it's out of your control).

like image 138
u3l Avatar answered Oct 13 '22 12:10

u3l