Java Reference
In-Depth Information
Let us define an array list of bank accounts and fill it with objects. (The
BankAccount
class has been enhanced from the version in
Chapter 3
. Each bank
account has an account number.)
ArrayList<BankAccount> accounts = new
ArrayList<BankAccount>();
accounts.add(new BankAccount(1001));
accounts.add(new BankAccount(1015));
accounts.add(new BankAccount(1022));
The
ArrayList
class is a generic class:
ArrayList<T>
collects objects of
type
T
.
The type
ArraList<BankAccount>
denotes an array list of bank accounts. The
angle brackets around the
BankAccount
type tell you that BankAccount is a type
parameter. You can replace
BankAccount
with any other class and get a different
array list type. For that reason,
ArrayList
is called a generic class. You will learn
more about generic classes in
Chapter 17
. For now, simply use an
ArrayList<T>
whenever you want to collect objects of type
T
. However, keep in mind that you
cannot use primitive types as type parametersČ there is no
ArrayList<int>
or
ArrayList<double>
.
When you construct an
ArrayList
object, it has size 0. You use the add method to
add an object to the end of the array list. The size increases after each call to add. The
size
method yields the current size of the array list.
To get objects out of the array list, use the get method, not the
[ ]
operator. As with
arrays, index values start at 0. For example,
accounts.get(2)
retrieves the
account with index 2, the third element in the array list:
BankAccount anAccount = accounts.get(2);
As with arrays, it is an error to access a nonexistent element. The most common
bounds error is to use the following:
int i = accounts.size();
anAccount = accounts.get(i);
// Error
The last valid index is
accounts.size() - 1
.