When is it better to use a vector than an array and vice versa in java? and why?
Each class has its own features and the class used to store a type of data determines how it can be accessed and manipulated. One of the most important classes in Java is the Vector class. Vector is an implementation of the List interface and is used to create resizable arrays.
1) ArrayList is not synchronized. Vector is synchronized. 2) ArrayList increments 50% of current array size if the number of elements exceeds from its capacity. Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity.
Performance: ArrayList is faster. Since it is non-synchronized, while vector operations give slower performance since they are synchronized (thread-safe), if one thread works on a vector, it has acquired a lock on it, which forces any other thread wanting to work on it to have to wait until the lock is released.
Vector
: never, unless an API requires it, because it's a class, not an interface.
List
: this should be your default array-like collection. It's an interface so anything can be a List
if it needs to. (and there are lots of List
implementations out there e.g. ArrayList
, LinkedList
, CopyOnWriteArrayList
, ImmutableList
, for various feature sets)
Vector
is threadsafe, but so is the Collections.synchronizedList()
wrapper.
array: rarely, if required by an API. The one other major advantage of arrays is when you need a fixed-length array of primitives, the memory space required is fairly compact, as compared to a List<Integer>
where the integers need to be boxed into Integer
objects.
A Vector
(or List
) when you don't know before hand how many elements are going to be inserted.
An array
when you absolutely know what's the maximum number of elements on that vector's whole life.
Since there are no high performance penalties when using List
or Vector
(any collection for that matter), I would always chose to use them. Their flexibility is too important to not be considered.
Nowadays I only use arrays
when I absolutely need to. Example: when using an API that requires them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With