Hal Vaughan said:
I've read up on Vectors and LinkedLists. Other than slightly different
interfaces, I'm not clear on reasons for using one over the other. Both
can keep growing and can have members inserted or removed as needed.
Is there a reason to use one over the other?
Short answer: yes.
Longer answer:
Vector, LinkedList, and ArrayList all implement the List interface. As such,
they all adhere to the contract of List: they contain objects in a
particular order, and offer methods to add objects to the list, remove
objects from the list, iterate over them (via an Iterator), and to access
objects by index in the list.
The differences come in the implementation.
Vector is basically a synchronized version of ArrayList. That is, all of the
methods on Vector have the "synchronized" keyword. That means that only one
thread at a time can access the internals of any given instance of Vector.
This is generally a Good Thing, but incurs the overhead of obtaining the
lock on the instance every time any method is called. If you have some other
guarantee that only one thread at a time can access any given Vector, then
this overhead is unnecessary, and you may as well use the (unsychronized)
ArrayList.
An ArrayList is implemented with a backing array. Inserts at the end are
fast (unless the backing array needs to be resized). Inserts in the middle
or at the front mean that all the other elements of the array need to be
copied to make room. Deletions mean that elements need to be copied down
from the end of the list. Iteration is fast; it means incrementing an index
into the array. Sorts are reasonably fast, as ArrayList supports O(1) random
access. Indexed access (via the "get(int)" method) is very fast.
A LinkedList is also unsynchronized. A LinkedList is implemented as a
doubly-linked chain of nodes. Inserts at the beginning or end are very fast.
Deletions from the middle are very fast (via the Iterator's "remove"
method), as a deletion only means moving two references. Iteration is fast;
it simply means walking the chain of nodes. Sorts are slow, as LinkedList
supports only O(n) random access. Indexed access (via the "get(int)" method)
is slow.