Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Vector - alternatives

Previously I would always have thought a Vector was good to use for non-descript objects when length was unknown. As far as I was aware I thought it was thread-safe too

What would change that Vector shouldn't be used anymore, and what is the alternative?

like image 450
ST. Avatar asked Nov 24 '09 18:11

ST.


People also ask

What can I use instead of Vector in Java?

Alternatives to the Vector Class If a thread-safe implementation of List interface is required, we can either use CopyOnWriteArrayList class, which is a thread-safe variant of the ArrayList or synchronize ArrayList externally using the synchronizedList() method of the Collections class.

Is Vector outdated in Java?

Vector class is often considered as obsolete or “Due for Deprecation” by many experienced Java developers. They always recommend and advise not to use Vector class in your code. They prefer using ArrayList over Vector class.

Is Vector better than ArrayList?

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.

Do we have vectors in Java?

Vector implements a dynamic array which means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index.


2 Answers

You should use ArrayList instead of Vector. Vector used internal synchronisation, but that is rarely good enough for actual consistency, and only slows down execution when it is not really needed.

Also see this stackoverflow question.

like image 116
Paul Wagland Avatar answered Oct 03 '22 05:10

Paul Wagland


You can use an ArrayList instead.

If you need a synchronized version, you can do something like:

ArrayList arrayList = new ArrayList();  List synchList = Collections.synchronizedList(arrayList); 
like image 40
hexium Avatar answered Oct 03 '22 04:10

hexium