Espresso: A Concentrated Introduction to Java
Summary: In this laboratory, you will explore some subtleties
of the utility class java.util.Vector
.
References:
Contents:
a. Create a package named
username.vectors
in project Code.
b. Open a separate window with
the reference for java.util.Vector
.
Write a main class, username.vectors.TestVector
that (a) builds an empty vector of Strings (using the zero-parameter
constructor) and (b) prints all the elements in the vector using code that
will continue to work if we add elements. Hint: You'll need a for loop.
As you may have noted, vectors provide two kinds of add
methods: One that adds to the end, and one that adds in a specified
location.
a. Verify that adding to the index 0 an empty vector succeeds.
(Use the two-parameter add
.)
b. Verify that adding to the end of that one-element vector succeeds.
(Use the one-parameter add
.)
c. What do you think will happen if you add an element at index 0 in this two-element vector?
d. Verify your answer to step c experimentally.
e. What do you think will happen if you add an element at index 10 in this new vector?
f. Verify your answer to step e experimentally.
As you may have noted, vectors provide two kinds of remove
methods: One that removes by index and one that removes by value. We
will focus on the first.
a. What do you expect to happen if you remove the element at index 0 in a non-empty vector?
b. Verify your answer experimentally.
c. What do you expect to happen if you attempt to remove an element at an index greater than the size of the vector?
d. Verify your answer experimentally.
As you may have noted, vectors also provide two mechanisms for setting
values in an array, set
and setElementAt
.
a. What, in your reading of the documentation is the difference between
set
and setElementAt
?
For the remaining parts of this exercise, use set
.
b. What do you expect to happen if you set the value at position 0 in an empty vector?
c. Verify your answer experimentally.
d. What do you expect to happen if you set the value at position 0 in a two-element vector?
e. Verify your answer experimentally.
f. What do you expect to happen if you set the value at position 2 in a two-element vector?
g. Verify your answer experimentally.
h. What do you expect to happen if you set the value at position 3 in a two-element vector?
i. Verify your answer experimentally.
Redo the previous exercise, using setElementAt
rather than
set
.
Explain the difference between add
(the two-parameter version),
set
, and setElementAt
.
Tuesday, 19 April 2005 [Samuel A. Rebelsky]
Tuesday, 25 October 2005 [Samuel A. Rebelsky]
Tuesday, 7 March 2006 [Samuel A. Rebelsky]
This page was generated by
Siteweaver on Thu Mar 30 15:24:44 2006.
The source to the page was last modified on Tue Mar 7 08:50:58 2006.
This page may be found at http://www.cs.grinnell.edu/~rebelsky/Espresso/Labs/vectors.html
.
You may wish to validate this page's HTML ; ; Check with Bobby