Java Reference
In-Depth Information
5.3.3
Other methods in class Vector
Class Vector contains other methods that will help you create and maintain a list
of objects. The ones you are most likely to use are listed below. See lesson page
5-5 of the CD for more explanation, or look at the Java API specs for Vector .
When removing one or more elements from v , those with higher indices than
the removed ones are shifted down. Thus, the size of the v is reduced by the num-
ber of elements removed.
Activity
5-5.2
v.toString() = a description of v of the form [v[0], v[1], …] .
v.contains(obj) = obj is an element of v ”.
v.indexOf(obj) = index of first object in v that equals obj ( -1 if none).
v.indexOf(obj, k) = index of first object in v with index at least k
that equals obj ( -1 if none).
v.lastIndexOf(obj)= index of last object in v that equals obj ( -1 if none).
v.lastIndexOf(obj, k)
= index of last object in v with index at most k
that equals obj ( -1 if none).
v.remove(i)
Remove v[i] and return the removed element.
v.remove(obj)
Remove from v the first object that equals obj and return
the value of “an element was removed” (a boolean).
v.removeRange(i, j)
Remove v[i..j] from v .
v.clear();
Remove all objects from v , so that its size is 0 .
5.3.4
Exercises on class Vector
E1. In the Interactions pane of DrJava, create a Vector vec —remember to
import java.util.* first— and add these strings to it: "one" , "two" , "four" .
Then, type the expression vec . What is its value? Next, execute the call:
vec.add(2, "three"); . Now, what is the value of expression vec ?
E2. In the Interactions pane of DrJava, create a Vector v1 that contains the val-
ues of these expressions: new Integer(1) , new Integer(3), new Integer(5).
Then, find out the value of expression v1 . Write down the values of the follow-
ing expressions (let DrJava evaluate them): v1.elementAt(1) ,
v1.elementAt(2) , and v1.size() .
E3. In the Interactions pane of DrJava, create a Vector v1 that contains the val-
ues of these expressions: new Integer(1) , new Integer(3), new Integer(5).
Then, find out the value of expression v1 . What happens when you execute this
assignment statement, and what do you have to do to fix it?
Integer middle= v1.elementAt(1);
E4. Write (and test) a boolean function with two arguments: a Vector v and an
Object x . The function returns the value of the sentence “ x occurs at least twice
Search WWH ::




Custom Search