Java Reference
In-Depth Information
list2.set(42, index);
//Sets the element at index to
//new Integer(42). This example relies on automatic boxing.
int
temp2 = list2.get(index);
//The expression
//v.get(index) returns the element at position index.
// This example relies on automatic unboxing.
The
index
must be greater than or equal to
0
and less than the current size of the
ArrayList
list
.
The two methods
set
and
get
give
ArrayList
s approximately the same functional-
ity that square brackets give to arrays. However, you need to be aware of one impor-
tant point: The method invocation
list.set(index, "Hi Mom!");
is
not
always completely analogous to
a[index] = "Hi Mom!";
The method
set
can replace any existing element, but you cannot use
set
to put an
element at just any index, as you could with an array. The method
set
is used to
change the value of elements, not to set them for the first time. To set an element for
the first time, you usually use the method
add
. The basic form of the method
add
adds
elements at index position
0
, position
1
, position
2
, and so forth in that order. This
means that
ArrayList
s must always be filled in this order. But your code can then go
back and change any individual element, just as it can in an array.
For example, suppose
list
is an
ArrayList
with base type
String
, which has not
yet had any elements added to it; that is,
list
is empty. The following statements will
add the strings
"One"
,
"Two"
, and
"Three"
to positions
0
,
1
, and
2
:
add
list.add("One");
list.add("Two");
list.add("Three");
The method name
add
is overloaded. There is also a two-argument method named
add
that 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
, ele-
ments at the specified index and higher (if any) are moved up one position to make
room for the new element. For example,
list.add(0, "Zero");
adds the string
"Zero"
at position
0
and moves elements originally at positions
0
,
1
,
2
,
and so forth up one position to positions
1
,
2
,
3
, and so forth.