Incremental Java
Introduction to ArrayList

Elements

A container class is a class that lets you control how many objects are in the class. The container is a balloon. In the balloon, there are several boxes. The number of boxes in the container is called its size. Each box is often called an element (or a cell).

Here are some of the things to do with the boxes in the container.

  • Get an object handle from one of the boxes
  • Put an object handle in one of the boxes
  • Add a new box and place an object handle in that box (the size increases by 1)
  • Remove one of the boxes
  • Remove all of the boxes
ArrayLists are convenient because they grow and shrink, depending on what the object user wants to do. This resizing is handled by the ArrayList object, so the user doesn't have to deal with it. (An array, on the other hand, requires the object user to handle the resizing, which is somewhat complicated).

Containers Hold Objects

We want ArrayList to be as flexible to use as possible. The best choice for the type of each box is Object, because any object type is a descendant class of Object, which means any object can be put into an ArrayList.

Unfortunately, primitive variables can't be put into an ArrayList. (There is hope. Each primitive type has an object type associated with it. For example, there is an Integer, Double, Character and Boolean class. Like other classes, these classes have methods, including constructors. They don't behave exactly like their primitive type counterparts, but with a little work, you can switch between the two types).

Index

In order to get an object handle from an ArrayList or to put one into an ArrayList, we need give some name or number to each box, so we can uniquely identify the box.

For ArrayList, each box is given a number, called the index. If an ArrayList has 3 boxes, then the indexes are 0, 1, and 2. Indexing always starts at 0. The maximum index is size - 1. Thus, if an ArrayList has 100 boxes, the minimum index is 0, and the maximum index is 99.

You might wonder why indexing starts at 0, instead of 1? There is a technical reason for it. Let's just say that it's easier for the Java compiler (by just a little bit) to start indexing at 0. In any case, programmers get used to 0 as the smallest index very quickly. You'll get used to it too. Give yourself a few months, and it will be natural to you.

With an index, we can retrieve an object handle at a particular box, or put a different object handle at a particular box.