ArrayLists and Iterators
Read this chapter about lists and the useful methods that are available for adding and inserting elements into a list.
4. ArrayList class
Answer:
An ArrayIndexOutOfBounds
exception is thrown and (usually) the program halts.
ArrayList
class
The ArrayList
class builds
upon the capabilities of arrays. An ArrayList
object contains an array of object references plus many methods for managing that array.
The biggest convenience of a ArrayList
is that you can keep adding elements to it no matter what size it was originally. The size of the ArrayList
automatically increases and no information
will be lost.
However, this convenience comes at a price:
- The elements of an
ArrayList
must be object references, not primitive data likeint
ordouble
. ArrayList
operations are slightly slower than array operations.
In the picture, "X" shows that a cell is empty. The ArrayList
in the picture is completely empty. The "X" is conceptual; the actual implementation of ArrayList
uses an unspecified means to keep track
of empty cells.
Note: "X" is not the value null
. If null
is placed in a cell, the cell is regarded as containing data.
Question 4:
(Thought Question: ) Say that you want a list of
int
values. But anArrayList
can contain only object references. How can you use anArrayList
to store yourint
s? (Click for a hint.)