Java Reference
In-Depth Information
Transaction aTransaction = (Transaction)transactions.remove(3);
Here we save a reference to the object that was removed in
aTransaction
. The cast is necessary
because the reference is returned as type
Object
.
Sometimes you'll want to remove a particular reference, rather than the reference at a given index. If
you know what the object is that you want to remove, you can use another version of the
remove()
method to delete it:
boolean deleted = transactions.remove(aTransaction);
This will search the vector
transactions
from the beginning to find the first reference to the object
aTransaction
and remove it. If the object is found and removed from the vector, the method returns
true
, otherwise it returns
false
.
Another way to remove a single element is to use the
removeElementAt()
method, which requires an
argument specifying the index position for the element to be removed. This is clearly similar to the version of
remove()
that accepts an index as an argument, the difference being that here the return type is
void
.
There is also a
removeAll()
method that accepts an argument of type
Collection
, which removes
elements from the collection passed to the method if they are present in the vector. The method returns
true
if the
Vector
object is changed by the operation, that is, at least one element was removed. You
could use this in conjunction with the
subList()
method to remove a specific set of elements:
transactions.removeAll(transactions.subList(5,15));
This will remove elements 5 to 14 inclusive from the
Vector
object
transactions
, plus any
duplicates of those objects that are in the vector.
The
retainAll()
method provides you with a backhanded removal mechanism. You pass a reference
of type
Collection
as the argument to the method that contains the elements to be retained. Any
elements not in the collection you pass to the method will be removed. For instance, you could keep the
elements at index positions 5 to 15 and discard the rest with the statement:
transactions.retainAll(transactions.subList(5,15));
The method returns
true
if the
Vector
has been changed - in other words if at least one element has
been removed as a result of the operation. The method will throw an exception of type
NullPointerException
if the argument is
null
.
If you want to discard all the elements in a
Vector
, you can use the
clear()
method to empty the
Vector
in one go:
transactions.clear(); // Dump the whole lot