Java Reference
In-Depth Information
you pass to the method are removed. For example, you could keep the elements at index positions 5 to 14,
inclusive, plus any duplicates of these elsewhere in the vector, and discard the rest with the following state-
ment:
names.retainAll(names.subList(5,15));
The method returns true if the vector has been changed — in other words, if at least one element has
been removed. The method throws a NullPointerException if the argument is null .
If you want to discard all the elements in a Vector , you can use the removeAllElements() method to
empty the Vector in one go:
names.removeAllElements(); // Dump the whole lot
This removes all the elements from the names vector and sets the size to zero. The clear() method that
is declared in the List<> interface is identical in function so you can use that to empty a vector if you prefer.
With all these ways of removing elements from a Vector<> object, there's a lot of potential for ending up
with an empty container. It's often handy to know whether or not a vector contains elements, particularly if
there's been a lot of adding and deleting of elements. You can determine whether a vector contains elements
by calling its isEmpty() method. This returns true if the vector's size is zero and false otherwise.
NOTE Note that if a Vector<> or ArrayList<> object contains only null references, it
doesn't mean the size() is zero or that the isEmpty() method returns true . To empty a con-
tainer you must actually remove all the elements, not just set the elements to null .
Searching for Objects
You get the index position of an object stored in a vector if you pass the object as an argument to the in-
dexOf() method. For example:
int position = names.indexOf(aName);
This searches the names vector from the beginning for aName using the equals() method for the argu-
ment, so your aName class type needs to have a proper implementation of equals() for this to work. The
variable position contains either the index of the first reference to the object in names , or −1 if the object
isn't found. The lastIndexOf() method works in a similar fashion, but the search is starting from the last
element back to the first.
Another version of the indexOf() method that is not available for an ArrayList<> accepts a second ar-
gument specifying the index position where the search for the object should begin. The main use for this
arises when an object can be referenced more than once in a vector. You can use the method in this situation
to recover all occurrences of any particular object, as follows:
String aName = "Fred"; // Name to be found
int count = 0; // Number of occurrences
int position = -1; // Search starting index
while(++position < names.size()) { // Search with a valid
Search WWH ::




Custom Search