Java Reference
In-Depth Information
17 System.out.println("list1 = " + list1);
18 System.out.println("list2 = " + list2);
19 }
20 }
The preceding code will produce the following output:
list1 = [1, 82, 97]
list2 = [7, -8]
You must implement three methods in this program: the constructor, the add
method, and the toString method that println will call. First you have to figure
out what kind of fields you need. We are trying to emulate the ArrayList class,
which is built on top of a simple array, so you should do the same thing for your
ArrayIntList class. All of the examples of arrays in Chapter 7 involved what could
be called filled arrays in which each element of the array is in use. A filled array
works fine in many applications, but this is not one of them. You are implementing a
dynamic structure that will grow and shrink as the client adds and removes values, so
you don't want to be forced to use an array that is exactly the same size as your list.
Instead, you should use an unfilled array in which some of the array elements are
in use and some are not. This approach is similar to the way that a hotel is run. A
hotel might have 100 guest rooms, but they don't all have to be occupied at once.
There might be 90 rooms currently in use by customers and 10 vacant rooms that are
available for later use.
This concept raises the question of how to distinguish between occupied cells and
vacant cells in the array. One simple approach is to maintain a size variable that
keeps track of the number of occupied cells and use the front of the array for cells
that are currently in use and the back of the array for cells that are vacant. Unlike a
hotel that has vacant occupied rooms interspersed, this kind of unfilled array groups
all of the occupied cells together at the front of the array and all of the vacant cells at
the end of the array.
For example, the sample client code at the beginning of this section constructs a
list and adds the values 1 , 82 , and 97 to the list. That would mean that three of the
array cells are occupied and any other cells are vacant. Suppose that you construct an
array variable called elementData and you add these three values as the first three
entries in the array:
[0]
[1]
[2]
[3]
[4]
[5]
[6] [7] [8] [9]
elementData
1
82
97
0
0
0
0
0
0
0
While it's true that the first vacant cell has the value 0 stored in it, you wouldn't
want to count on this being the case because the client might want to store the value 0
in the list. Without a size variable, you wouldn't know for sure whether this list ends
with 97 or whether it ends with one of the zeros. With the size variable, you can
 
Search WWH ::




Custom Search