Incremental Java
What is a Container?

Objects are a Container for Instance Variables

We've said that an object is a container for instance variables. As a class designer, you must pick some instance variables when you implement a class. The number of variables is a choice that you, the class designer makes, but once that choice is made, it's made. The object user can't increase or decrease the number of instance variables in an object (in general, objects users don't even have direct access to the instance variables).

But what happens if you want an object to have the number of boxes vary as needed. Let's think of an analogy. You are having some friends over to your place, and you are somewhat cheap. You have many folding chairs that stay folded when no one is around.

Each time a guest arrives, you open a folding chair so they can sit down. Each time a guest leaves, you close the folding chair, so it doesn't take up space. You have as many chairs as guests, and no more.

What is a Container?

We would like to have objects that can hold a varying number of other objects. A container is a generic name for just such an object.

For example, suppose you have a small college. There are several hundred students. Each semester, all students who have a GPA of 3.5 or higher are placed on the Dean's List, recognizing their achievements. Each semester, the number of students on the Dean's List varies. Sometimes there are lots of students, sometimes not so many.

You wish to write a program that finds all students who should be on the Dean's List, and sends them email to congratulate them.

One way to do this is to have a list of students in some container object. Then, go through the entire list, one at a time, and check the GPA. If the GPA is 3.5 or higher, add a copy the Student handle to another container, that holds the students on the Dean's List. Once you've done processing the list, go through the new container, and email each person on that list.

Features of a Container

A container is a general name for an object that can hold 0 or more other objects. Its size can vary. Here are some common operations for a container.
  • You can add objects to a container
  • You can remove objects from a container
  • You can clear the entire container
  • You can ask how big the container is (how many objects in it)
  • You can ask for individual objects (by providing an index)
We're going to study a container class in Java called ArrayList. We'll look at its methods, and then write some programs.

We'll also look at arrays. Arrays don't have the same kind of flexibility as ArrayList. Nevertheless, they are important in many languages, including Java. In general, we'll favor using ArrayList over arrays.

Then, we'll implement a simple ArrayList using arrays so you can get an idea of how to write your own ArrayList.