Java Reference
In-Depth Information
The
size
Method
The method
size
returns the number of elements in an
ArrayList
.
EXAMPLE
for
(
int
index = 0; index < list.size(); index++)
System.out.println(list.get(index));
list
is an
ArrayList
object.
TIP: Summary of Adding to an
ArrayList
To place an element in an
ArrayList
position (at an
ArrayList
index) for the first
time, you usually use the method
add
. The simplest method named
add
has a single
parameter for the element to be added and adds elements at index positions
0
,
1
,
2
,
and so forth, in that order.
You can add an element at an already occupied list position by using the two-parameter
version of
add
. When inserting into an
ArrayList
with this version of
add
, elements at
the specifi ed index and higher are moved up one position to make room for the new ele-
ment. For example, suppose
list
is an
ArrayList
object with base type
String
that has
three elements already on its list. Consider the following method invocation:
list.add(1, "Amor");
Before, there were elements at index positions
0, 1
, and
2
. When this invocation of
add
is executed, the element
"Amor"
is inserted at index
1
, and the elements at index
positions
1
and
2
are moved to positions
2
and
3
.
You can also use the two-argument version of
add
to add an element at the fi rst
unused position. If
list
has elements at index positions
0, 1, 2
, and
3
, then the fol-
lowing is legal:
list.add(4, "Mucho Amor");
Your code can then go back and change any individual element, using
set
. However,
set
can reset only the element at an index that already has an element.
The method
size
can be used to determine how many elements are stored in an
ArrayList
.
add
■
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
position
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
?