Java Reference
In-Depth Information
Answers to Self-Test Exercises
1.
list.add("Hello");
2.
instruction
.set(5, "Go");
3.
instruction
.add(5, "Go");
4. No. The index for
set
must be greater than or equal to
0
and less than the size of
the
ArrayList
. Thus, you can replace any existing element, but you cannot place
the element at any higher index. This
situation
is unlike that of an array. If an
array is partially filled to index
10
, you can add an element at index
20
, as long as
the array is that large. With an
ArrayList
, you cannot add an element beyond
the last-used index.
5. No. The index for
add
must be greater than or equal to
0
and less than or equal
to the size of the
ArrayList
. Thus, you can replace any existing element or add
an element to the end of the list, but you cannot place the element at any higher
index. This situation is unlike that of an array. If an array is partially filled to
index
10
, you can add an element at index
20
, as long as the array is that large.
With an
ArrayList
, you cannot add an element beyond one more than the last-
used index.
6. The index for
add
(that is,
index2
) is allowed to be one larger than the index for
set
(that is,
index1
). The index for
set
must be strictly less than the size of the
ArrayList
. The index for
add
can also be equal to the size of the
ArrayList
.
7. Yes. The
ArrayList
can contain more than 20 elements. The number
20
used as
an argument to the constructor merely gives the initial memory allocation for the
ArrayList
. More memory is automatically allocated when it is needed.
8.
for
(Double element : numberList
)
System.out.println(element);
9.
import
java.util.ArrayList;
/**
Class for sorting an ArrayList of Strings lexicographically
(approximately alphabetically).
*/
public class
StringSelectionSort
{
/**
Sorts
the
ArrayList
a
so
that
a.get(0),
a.get(1),...,
a.get(a.size()
−
1) are
in
lexicographic order.
*/
public static void
sort(ArrayList<String> a)
{
int
index, indexOfNextSmallest;
for
(index = 0; index < a.size()
−
1; index++)
{
//Place the correct value in position index: