Java Reference
In-Depth Information
Suppose
list
starts out empty and your code executes our four
add
invocations,
which we repeat below:
list.add("One");
list.add("Two");
list.add("Three");
list.add(0, "Zero");
After these four invocations of
list.add
, the
list
would contain the strings
"Zero"
,
"One"
,
"Two"
, and
"Three"
in positions
0
,
1
,
2
, and
3
, respectively.
Note that the two-argument version of
add
cannot add an element at just any
position. It can only insert an element at some already used position or at the first unused
position. The elements in an
ArrayList
always occupy a contiguous set of positions
starting at
0
; that is, they are always at positions
0
,
1
,
2
, and so forth up to some last
position. This is just like a partially filled array (as discussed in Chapter 6), but unlike a
partially filled array, you do not need to do anything to keep track of how many elements
are on the list. The method
size
automatically takes care of this for any
ArrayList
.
The
add
Methods
Elements can be added to an
ArrayList
by using the methods named
add
. The elements
are added to index position
0
, then
1
, then
2
, and so forth so there are no gaps in the indices
of elements.
The most straightforward method to use for adding to an
ArrayList
is the method named
add
that has only one parameter.
EXAMPLES
list.add("Salud");
list.add("Dinero");
list.add("Java");
The object
list
is an
ArrayList
with base type
String
.
A second method named
add
allows you to add an element at any currently used index
position or at the first unused position. When inserting into an
ArrayList
with this version
of
add
, elements at the specified index and higher (if any) are moved up one position to
make room for the new element.
list.add(1, "Amor");
If
list
starts out empty and all four statements in the two sets of examples are executed,
then
list
would contain the following strings in the order given:
"Salud"
,
"Amor"
,
"Dinero"
, and
"Java"
.
You can find out how many indices already have elements by using the method
size
. If
list
is an
ArrayList
,
list.size()
returns the
size
of the
ArrayList
,
which is the number of elements stored in it. The indices of these elements go from
0
to one less than
list.size()
.
size