Java Reference
In-Depth Information
public void clear(). Removes all the elements from the Vector, causing
the Vector to become empty. The same result can be achieved by using
the public void removeAllElements() method.
public Object remove(int index). Removes the Object at the specified
index and returns a reference to the Object. The same result can be
achieved by using the public void removeElementAt(int index) method.
public boolean remove(Object element). Removes the first occurrence
of the specified Object, as determined by the equals() method. The
return value is true if the Vector actually contained and removed the ele-
ment Object. The same result can be achieved by using the public
boolean removeElement(Object element) method.
public boolean removeAll(Collection c). Removes the elements in the
Vector that appear in the given Collection. The method returns true if the
Vector is changed.
public boolean retainAll(Collection c). Removes the elements in the
Vector that do not appear in the given Collection. The method returns
true if the Vector is changed.
public void setElementAt(Object element, int index). Adds the given
Object to the Vector at the specified index, removing any previous ele-
ment at that index.
The Vector class also contains various methods for accessing the elements in
the Vector, as well as obtaining general information about the Vector. Some of
these methods include the following:
public Object get(int index). Returns a reference to the element in the
Vector at the specified index. The public Object elementAt(int index)
method can also be used for this purpose.
public Object firstElement(). Returns the element at index 0.
public Object lastElement(). Returns the last element in the Vector.
public int indexOf(Object element). Returns the index in the Vector of
the first occurrence of the given element as determined by the equals()
method. The return value is -1 if the element is not found.
public Object [] toArray().
Returns an Object array containing all the ele-
ments in the Vector.
The VectorDemo2 program, shown in the following listing, demonstrates
using some of these methods for accessing and removing elements from a Vec-
tor. Note that the Employee class was modified to include an equals() method
that returns true if two Employee objects have the same number. Study the
program and try to determine its output, which is shown in Figure 9.9.
Search WWH ::




Custom Search