Saturday, August 08, 2009

ArrayList vs Vector

Internally, Vector and ArrayList holds their contents using an array. From API point of view, vector and arraylist are very similar. Vectors are synchronized, where as ArrayList are not. Sometimes its better to use Vector, sometimes its better to user ArrayList. Your choice depends upon the needs. Following are the similarities and differences between the two.

Similarities between ArrayLists and Vectors

  • Both can grow up during run time.
  • Both implement List interface.
  • With both, it is easier to remove or add elements at the end or start, but if you try to add or remove elements somewhere at middle of collection, they suffer performance wise. (Use LinkedLists if your programme need to do that a lot, but LinkList requires more memory and computation)

Differences between ArrayLists and Vectors

  • The major difference is just that vectors are synchronized. This means that if more than one thread in your code is to use that data, you are in trouble with ArrayList as the data is asynchronous. Though there are ways by which you can make your ArrayLists synchronous, but by default they are not. The obvious downside with vectors is the additional computation to handle threads.
  • Vector contains many legacy methods that are not part of collection framework. With Java2 release, Vector reengineered to extend the class AbstractList and implements List interface, now it is fully compatible with collections framework.
  • The other difference is that with vectors, you can specify the incremental value, which is the amount with which the data structure will grow during the runtime. But with ArrayLists you have no option but to accept default that is the list will grow up 50% of original size everytime it needs additional space. It is advisable in both the cases to choose the initial size carefully.

1 comment:

È