Java Reference
In-Depth Information
Self-Test Exercises
1.
Suppose
list
is an object of the class
ArrayList<String>
. How do you add the string
"Hello"
to the
ArrayList
list
?
2. Suppose
instruction
is an object of the class
ArrayList<String>
that contains
the string
"Stop"
at index position
5
. How do you change the string at index posi-
tion
5
to
"Go"
(without changing any of the elements at other positions)?
3. Suppose
instruction
is an object of the class
ArrayList<String>
that contains
strings at index positions
0
through
10
. How do you insert the string
"Go"
at
index position
5
so that no strings are removed from the list
instruction
?
4. Can you use the method
set
to place an element in an
ArrayList
at any index
you want?
5. Can you use the two-argument version of the method
add
to add an element in an
ArrayList
at any index you want?
6. Consider the following two method invocations. Are there values of
index1
that are allowed but that are not allowed for
index2
? Are there values of
index2
that are allowed but that are not allowed for
index1
?
list
is an object of the class
Array-List<String
>.
list.set(index1, "Hello");
list.add(index2, "Hello");
7. If you create an
ArrayList
with the following statement, can the
ArrayList
con-
tain more than 20 elements?
ArrayList<Double> myList =
new
ArrayList<Double>(20);
Methods in the Class
ArrayList
With arrays, the square brackets and the instance variable
length
are the only tools
automatically provided for you, the programmer. If you want to use arrays for other
things, you must write code to manipulate the arrays.
ArrayList
s, on the other hand,
come with a selection of powerful methods that can do many of the things for which
you would need to write code in order to do with arrays. For example, the class
Array-
List
has a version of the method
add
that inserts a new element between two elements
in the
ArrayList
. Most of these methods are described in Display 14.1.
Display 14.1
Some Methods in the Class
ArrayList
(part 1 of 4)
CONSTRUCTORS
public
ArrayList<
Base_Type
>(
int
initialCapacity)
Creates an empty
ArrayList
with the specified
Base_Type
and initial capacity.
(continued)