Return to lecture notes index

15-100 Lecture 21 (Monday, October 30, 2006)

Quick Quiz

// Write a code segment, not a full method spec, not a full class spec. Do NOT use Scanner 
// or BufferedReader for anything! 

// 1. Declare and otherwise create an array called "numbers"
int[] numbers = new int[10];

// 2. Populate the array with 10 numbers -- use a method called "getOneInt()" to get the 
// individual numbers
for (int index=0; index < 10; index++)
  numbers[index] = getOneInt();

// 3. Traverse (walk through) the array using a for-loop and find the minimum value
int lowest=numbers[0];
for (int index=1; index < 10; index++)
  if (numbers[index] < lowest)
    lowest = numbers[index];


// 4. Print this minimum value
System.out.println (lowest);

Today's Example

Today, we're going to create a generic Container based on an array of objects. The idea is that we'll be able to add and remove things from this Container, as well as to determine if an Object is already within the container.

The example serves to illustrate the use of arrays -- both their syntax and sematics, and also how they can be used in practice.

The Storage

Storage within the Container is based on an array of Objects. We choose to create an array of Objects, becuase it enables this Container to hold anything, because all objects are derived from Object and all primitives can be wrapped within Objects (more on that soon).

We initialize the array when the Container is created, via the constructor. But, how big should it be? We'll answer that question two ways:

...this way, we can accomodate the expected common cases -- and also much larger cases.

We also keep an instance variable, count, that serves to tell us the next available slot in the array -- in other words, where we put the next item. Since the array's first index is 0, this variable also contains the count of items -- it is initially 0 and remains one ahead of the most recently added item.

In creating the class, we'll use a "final" variable to set the default size. Since this is a definition, not a property of an instance, we make it "static". This type of variable is known as a "configuration constant". This is because it can be changed, a.k.a., configured, but only before the program is compiled, hence "constant" during the program's execution.

class Containter {

  private Object[] items;
  private int count;
  
  private static final int DEFAULT_SIZE = 10;
  

  public Container() {
    items = new Object[DEFAULT_SIZE];
    count = 0;
  }
  
  
  public Container (int size) {
    items = new Object[size];
    count = 0;
  }

}

The add(...) Method

The add method is, in principle, very straight-forward. We have our state variable, count, that maintains the position of the next available slot. We drop our item off into this slot and then advance the count counter.

About the only thing that can go wrong is that the array is already full. If the array is already full, (count == items.length). This is because an array of length items.length has indexes [0...(items.length-1)] -- but not items.length. Should we try to access an element outside of the legal bounds, an ArrayIndexOutOfBoundsException will be thrown. This is an "unreported" exception, so it doesn't need to be "declared thrown", but it certainly can and will arise.

Notice that after adding an item, we bump count forward -- this gets us ready to to it again for the next one.


  public void add (Object item) {
    if(count == items.length)
	grow();
    items[count++] = item;
  }

The grow() Method

Fortunately, that's not as hard as it seems. Remember that "list" is not an array -- it is a reference variable. It identifies an array. The user accesses the array only indirectly through it. This is called "indirection". And, the great thing about it is that the user doesn't need to know which array object is being used -- just that it is referenced by "list".

This makes it possible for us to play the shell game and switch the array underneath list from the small, filled array to a new bigger one. And, the user of list will never know the difference.

So, the solution looks like this:

  1. We create a new,bigger array
  2. We copy each reference from the old array to the new array, keeping it at the correpsonding index. Item 0 to item 0, item 1 to item 1, &c.
  3. We change "list" to reference the new array instead of the old array
  4. The garbage collector is now free to take care of the unreferenced old array.
  5. The user can't tell the difference -- they are still using list and everything is still at the same position.
So, our basic approach will be to create a new, bigger array to replace the old one. But, how much bigger? In a technical sense, we solve the problem if we make it only one slot larger -- then our insert can succeed.

But the problem is that we'll end up growing the array each time -- and that ain't cheap. Consider an array with 1,000,000,000 items. It it full, so we create one with 1,000,000,001 items. This involves copying the references for each fo the original 1,000,000,000 items. Now, we add one more, so we copy 1,000,000,001 items. And, each time we insert, we'll end up doing the same thing.

Ouch! So, we clearly want to grow by more than one. Typically these data structures grow by doubling. This way, there is plenty of room to grow. In 15-211 you'll learn that this approach leads to a reasonable average cost, known as :"amortized constant time". For now, we can just use our intuition and see that we end up copying a lot less this way. We're trading space for time -- a classic trade.

But, since this trade might be made differently if we knew that the array was large and wouldn't grow very often versus if it were small and dynamic, we make this growth factor a "configuration constant". A constant that can be changed in one place at compile time.

 private void grow() {
    Object[] biggerArray = new Object[GROWTH_COEFF * items.length];
  
    for (int index=0; index < items.length; index++)
      biggerArray[index] = items[index];
  
    items = biggerArray;
  }

Container, so far

class Containter {

  private Object[] items;
  private int count;
  
  private static final int DEFAULT_SIZE = 10;
  private static final int GROWTH_COEFF = 2;
  

  public Container() {
    items = new Object[DEFAULT_SIZE];
    count = 0;
  }
  
  
  public Container (int size) {
    items = new Object[size];
    count = 0;
  }
  

  public void add (Object item) {
    if(count == items.length)
	grow();
    items[count++] = item;
  }

  private void grow() {
    Object[] biggerArray = new Object[GROWTH_COEFF * items.length];
  
    for (int index=0; index < items.length; index++)
      biggerArray[index] = items[index];
  
    items = biggerArray;
  }

}