Wednesday, May 2, 2007

Difference between ArrayList and Vector class?

From an API perspective, the two classes are very similar.

Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList.

Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element 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. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It's always best to set the object's initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

2 comments :

JP@core java interivew questions on June 18, 2011 at 12:49 AM said...

Great article and you have indeed covered the topic quite well I have also blogged about Java Arraylist in Java 5 some time back , may be you find interesting.

Anonymous said...

great article

 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker