Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it better to use a vector than an array and vice versa in java?

Tags:

java

When is it better to use a vector than an array and vice versa in java? and why?

like image 948
David Avatar asked May 07 '11 22:05

David


People also ask

When should we use Vector in Java?

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.

What is the difference between an array and a Vector in Java?

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.

Which is better ArrayList or Vector?

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.


2 Answers

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.

like image 103
Jason S Avatar answered Nov 15 '22 12:11

Jason S


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.

like image 26
Pablo Santa Cruz Avatar answered Nov 15 '22 10:11

Pablo Santa Cruz