Java Reference
In-Depth Information
Storing Objects in a Vector
The simplest way to store an object in a
Vector
is to use the
add()
method as we did in the last
example. To store a transaction in the
transactions
vector, you could write:
transactions.add(aTransaction);
This will add a reference to the object
aTransaction
to the
Vector
object called
transactions
.
The new entry will be added at the end of the existing objects in the vector, and the size of the
Vector
will be increased by 1. All the objects that were already stored in the
Vector
remain at their
previous index position.
You can also store an object at a particular index position in a
Vector
using another version of
add()
that has two parameters. The first argument is the index position and the second argument is the object
to be stored. The index value must be less than or equal to the size of the
Vector
, which implies that
either there is already an object reference at this position or it is the position at the end of the
Vector
that is next in line to receive one. The index value is the same as for an array - an offset from the first
element - so you reference the first element using an index value of zero. For example, to insert the
object
aTransaction
as the third entry of
transactions
, you would write:
transactions.add(2, aTransaction);
The index value is of type
int
, and represents the index value for the position of the new object. The
new object,
aTransaction
, is inserted in front of the object that previously corresponded to the index
value 2, so objects stored in elements with index values equal to or greater than 2 will be shuffled along,
and their index values will increase by 1. If you specify an index value argument that is negative, or
greater than or equal to the size of the
Vector
, the method will throw an
ArrayIndexOutOfBoundsException
.
To change an element in a vector you use the
set()
method. This accepts two arguments: the first argument
is the index position where the object specified by the second argument is to be stored. To change the third
element in the
Vector
object
transactions
to
theTransaction
, you would write:
transactions.set(2, theTransaction);
The method returns a reference of type
Object
to the object that was previously stored at this position.
This gives you a chance to hang on to the displaced object if you want to keep it. If the first argument is
negative, or is greater than or equal to the current size of the
Vector
, the method will throw an
ArrayIndexOutOfBoundsException
.
You can add all the objects from another collection to a vector, either appended at the end or inserted
following a given index position. For instance, to append the contents of a
LinkedList
object,
myList
, to a
Vector
object,
transactions
, you would write:
transactions.addAll(myList);