1.
Declare and construct an array list that holds Employee objects:
ArrayList<Employee> staff = new ArrayList<Employee>();
You can also pass an initial capacity to the ArrayList constructor:
ArrayList<Employee> staff = new ArrayList<Employee>(100);
2.
Add new elements:
staff.add(new Employee("Harry Hacker", . . .));
API:
boolean add(T obj)
3.
If you already know, or have a good guess, how many elements you want to store, then call the ensureCapacity method before filling the array list:
staff.ensureCapacity(100);
4.
The size method returns the actual number of elements in the array list. For example,
staff.size()
5.
You should only use trimToSize when you are sure you won't add any more elements to the array list.
API:
void trimToSize()
6.
To set the ith element, you use
staff.set(i, harry);
API:
void set(int index, T obj)
puts a value in the array list at the specified index, overwriting the previous contents.
To get an array list element, use
Employee e = staff.get(i);
for (Employee e : staff) {...}
7.
You can sometimes get the best of both worlds—flexible growth and convenient element access—with the following trick. First, make an array list and add all the elements.
ArrayList<X> list = new ArrayList<X>();
while (. . .)
{
x = . . .;
list.add(x);
}
When you are done, use the toArray method to copy the elements into an array.
X[] a = new X[list.size()];
list.toArray(a);
8.
CAUTION:
Use the add method instead of set to fill up an array, and use set only to replace a previously added element.
9.
Instead of appending elements at the end of an array list, you can also insert them in the middle.
int n = staff.size() / 2;
staff.add(n, e);
10.
Employee e = staff.remove(n);
API:
T remove(int index)
removes an element and shifts down all elements above it. The removed element is returned.
11.
If you store many elements and frequently insert and remove in the middle of a collection, consider using a linked list instead.