Wednesday, August 4, 2010

ArrayList vs Vectors

Many people coming from Java 1.4 era seem to have a liking for Vectors. Before the Collections framework brought with it loads of classes, Vectors were a good option to fall back on when you wanted a growable array of objects. Vectors did the job well, but then, there are differences how Vectors and ArrayLists work. So, don't just jump and adopt Vectors if what you need is just an ArrayList. I am listing down a comparison between the two.

  • Vectors are synchronized while ArrayLists are not. So, if you need to work within a multi-threaded environment, then choose Vectors. But, if you don't even know what multi-threading is, or you do not want the access to be synchronized, use ArrayList. ArrayLists will give you a performance improvement over Vectors in a non-multi-threaded environment.
  • When Vectors grow, they do so by a factor of 2, while ArrayList grow by a factor of 1.5. In most of the cases, this fact doesn't matter. But, if you are writing alogrithms and performance intensive code, you should consider this difference.
  • The growth factor can be adjusted for a Vector, if you really need to change that. But for ArrayLists, this cannot be changed.
  • Both ArrayLists and Vectors have excellent performance when it comes to retrieving elements by index. Updating through indexes are also fast.