Java Reference
In-Depth Information
Fig. 4.7
Server providing '
Vector
ised' data to client in preceding screenshot
4.10
Vectors Versus ArrayLists
As an alternative to using an
ArrayList
to 'wrap up' our class objects, we could
choose to use a
Vector
. This class existed in Java before the Collection Framework
came into existence and was 'retro-fi tted' to take its place alongside the other
Collection classes. The only signifi cant difference is that, instead of using method
get
to retrieve an object from a
Vector
, we need to use method
elementAt
.
Example
Vector<String> stringVector = new Vector<>();
stringVector.add("Example");
//Next step retrieves this element.
String word = stringVector.elementAt(0);
Another slight difference is that, as well as having method
add
to add objects to
a
Vector
, there is also method
addElement
, principally to cater for older code.
The following question naturally arises: 'Which is it better to use—Vectors or
ArrayLists?'. The answer is… it depends! The
ArrayList
is faster, but is not thread-
safe, whereas the
Vector
is
thread-safe. Consequently, if thread-safety is important
to your program, you should use a
Vector
. If, on the other hand, thread-safety is not
a factor, then you should use an
ArrayList
.
Search WWH ::
Custom Search