Java Reference
In-Depth Information
{
<
Implementation deferred
>
}
// end replace
public
T getEntry(
int
givenPosition)
{
<
Implementation deferred
>
}
// end getEntry
public boolean
contains(T anEntry)
{
<
Implementation deferred
>
}
// end contains
public int
getLength()
{
return
numberOfEntries;
}
// end getLength
public boolean
isEmpty()
{
return
numberOfEntries == 0;
// or getLength() == 0
}
// end isEmpty
public
T[] toArray()
{
// the cast is safe because the new array contains null entries
@SuppressWarnings(
"unchecked"
)
T[] result = (T[])
new
Object[numberOfEntries];
for
(
int
index = 0; index < numberOfEntries; index++)
{
result[index] = list[index];
}
// end for
return
result;
}
// end toArray
// Doubles the size of the array list if it is full.
private void
ensureCapacity()
{
if
(numberOfEntries == list.length)
list = Arrays.copyOf(list, 2 * list.length);
}
// end ensureCapacity
<
This class will define two more private methods that will be discussed later.
>
}
// end
AList
13.6
The core methods.
As we just mentioned, we have chosen to implement the first
add
method and
the method
toArray
before the others, as they are central, or core, to our class. Adding a new
entry to the end of the list is easy; we simply add the entry to the array immediately after its last
occupied location. Of course, adding a new entry is possible only if the array has available space.
We call the private method
ensureCapacity
to resize the array if necessary. Thus, the first
add