Java Reference
In-Depth Information
Programming Tip:
When increasing the size of an array, you copy its entries to a larger
array. You should expand the array sufficiently to reduce the impact of the cost of copying. A
common practice is to double the size of the array.
Note:
Importing a class
The definition of a class that uses a class from the Java Class Library must be preceded by a
import
statement. For example, to use the class
Arrays
, you would write the following state-
ment prior to your class definition and its descriptive comments:
import java.util.Arrays;
Some programmers replace
Arrays
in this statement with an asterisk to make all classes in
the package
java.util
available to their program.
Note:
To say that we “resize” an array is really a misnomer, since an array's length cannot
be changed. The process of resizing an array involves creating a completely new array that
contains the entries of the original array. The new array is given the name of the original
array—in other words, a reference to the new array is assigned to the variable that had refer-
enced the original array. The original array is then discarded.
Question 18
Consider the array of strings that the following statement defines:
String[] text = {"cat", "dog", "bird", "snake"};
What Java statements will increase the capacity of the array
text
by five elements without altering
its current contents?
Question 19
Consider an array
text
of strings. If the number of strings placed into this
array is less than its length (capacity), how could you decrease the array's length without
altering its current contents? Assume that the number of strings is in the variable
size
.
The approach.
We can revise the previous implementation of the ADT bag by resizing the array
bag
so that the bag's capacity is limited only by the amount of memory available on your computer.
If we look at the outline of the class
ArrayBag
in Listing 2-1, we can see what we need to revise.
Let's itemize these tasks:
Change the name of the class to
ResizableArrayBag
so we can distinguish between our two
implementations.
●
Remove the modifier
final
from the declaration of the array
bag
to enable it to be resized.
●
VideoNote
Change the name of the constant
DEFAULT_CAPACITY
to
DEFAULT_INITIAL_CAPACITY
.
Although unnecessary, this change clarifies the new purpose of the constant, since the bag's
capacity will increase as necessary. Make the same change in the default constructor, which
uses the constant.
A resizable bag
●
Change the names of the constructors to match the new class name.
●