Array Lists Click here for the syntax in Java 7
The ArrayList class manages a sequence of objects
Can grow and shrink as needed
ArrayList
class supplies methods for many common tasks,
such as inserting
and removing elements
The ArrayList class is a generic class: ArrayList<T> collects objects of type T:
ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
accounts.add(new BankAccount(1001));
accounts.add(new BankAccount(1015));
accounts.add(new BankAccount(1022));
size method yields number of elements
Retrieving Array List Elements
Use get method
Index starts at 0
BankAccount anAccount = accounts.get(2); // gets the third element of the array list
Bounds error if index is out of range
Most common bounds error:
int i = accounts.size();
anAccount = accounts.get(i); // Error
//legal index values are 0. . .i-1
Adding /Removing /Changing Values of Elements
set overwrites an existing value
BankAccount anAccount = new BankAccount(1729);
accounts.set(2, anAccount);
add adds a new value before the index i
accounts.add(i, a);
Process of adding an element:
1. Resize the array list (increase by one)
2. copy the last one to the new spot. Keep moving until the space of i is available.
•To remove an element at an index, use the remove method:
account.remove(1);
How do you construct an array of 10 strings? An array list of strings?
Answer:
new String[10];
new ArrayList<String>();
What is the content of names after the following statements?
ArrayList<String> names = new ArrayList<String>();
names.add("A");
names.add(0, "B");
names.add("C");
names.remove(1);
Answer: names contains the strings "B" and "C" at positions 0 and 1