Java Reference
In-Depth Information
keep track of exactly how many cells are occupied and you know that all others are
vacant:
occupied
vacant
[0]
[1]
[2]
[3]
[4]
[5]
[6] [7] [8] [9]
elementData
1
82
97
0
0
0
0
0
0
0
In the preceding example, the array has a length of 10. We refer to this length as the
capacity of the list. In our hotel analogy, the hotel has 100 rooms, which means that it
has the capacity to rent up to 100 rooms. But often the hotel is not filled to capacity.
The same will be true for your list. The size variable keeps track of how much of the
list is currently occupied while the capacity tells you how large the list can grow.
The fields you want to declare for your class are an array and a size variable:
public class ArrayIntList {
private int[] elementData;
private int size;
...
}
Your constructor should initialize these fields. The array in the preceding example
had a capacity of 10, but let's increase it to 100:
public class ArrayIntList {
private int[] elementData;
private int size;
public ArrayIntList() {
elementData = new int[100];
size = 0;
}
...
}
Recall from Chapter 8 that fields are initialized to the zero-equivalent for the type,
which means that the size field will be initialized to 0 with or without the line of
code in the constructor. Some Java programmers prefer to leave out the line of code
because they are familiar with the default initialization. Others prefer to be more
explicit about the initialization. This is somewhat a matter of personal taste.
Now that you have the fields and constructor defined, you can turn your attention
to the add method. It takes an integer as a parameter. The idea is that you should
append the given value to the end of the list. The method will look like this:
public void add(int value) {
...
}
 
Search WWH ::




Custom Search