Java Reference
In-Depth Information
7.4 The Interface of an
ArrayList
Since
ArrayList
is a class, the interface of objects of type
ArrayList
is a lot different
than the interface of arrays. For example, the interface [] to access the element of an array
is not supported. An element of an
ArrayList
can be accessed using the
get(i)
method,
where
i
is the index of the element. The
size
method returns the numbers of elements in
the
ArrayList
.Thisdiffersfromthevariable
length
, which returns the size of the array
and not the number of elements in it. In fact, the variable
length
is not defined for an
ArrayList
because, by definition, an
ArrayList
can store a variable number of elements
and does not have preset capacity. To demonstrate how an
ArrayList
works, the following
method converts an
ArrayList
of employees to an array of employees.
public static
Employee [ ] convert(ArrayList
<
Employee
>
emps)
{
Employee [ ] result =
new
Employee [ emps . s ize () ] ;
for
(
int
i=0; i
<
emps . s i z e ( ) ;
i ++)
{
result [ i ] = emps.get(i);
return
result ;
}
The above method is for demonstration purposes only and it is not the easiest way to
convert an
ArrayList
to an array. Actually, Java supports the
toArray
method that will
convert any
ArrayList
into an array. The only caveat of using this method is that the result
needs to be cast to the proper array of objects. For example, the following code converts
an
ArrayList
of employees to an array of employees.
Employee [ ] emps = (Employee [ ] ) empArrayList . toArray () ;
Note that the
get
method is not identical to the [.] operator for arrays. For example,
we can write:
emps [ 0 ] =
new
Employee(
"John"
);
but we cannot use the following syntax.
emps . get (0) =
new
Employee(
"John"
);
The
get
method simply retrieves an element from the
ArrayList
and cannot be used
to modify an element of the
ArrayList
. An element of an
ArrayList
can be modified as
follows.
emps . set (0 ,
new
Employee(
"John"
));
The first parameter of the
set
method is the index in the
ArrayList
, while the sec-
ond parameter is the new value of the element. Note that the
set
method can only be
used to modify an existing element of an
ArrayList
.Itcannotbeusedtocreateanel-
ement at a position that does not exist. For example, the following code will generate
IndexOutOfBoundsException
exception.
ArrayList
<
Employee
>
emps =
new
ArrayList
<
Employee
>
() ;
emps . set (0 ,
new
Employee(
"John"
));
The reason is that the code tries to change the element at position 0, but an element at
position 0 does not exist. The correct approach is to use the
add
method to insert a new
element in the
ArrayList
. Here is the correct version of the above code.
ArrayList
<
Employee
>
emps =
new
ArrayList
<
Employee
>
() ;
emps . add(
new
Employee(
"John"
));