Java Reference
In-Depth Information
9 }
10
11
/** Construct a stack with the specified maximum capacity */
public
StackOfIntegers(
int
capacity)
12
{
13 elements =
new int
[capacity];
14 }
15
16
/** Push a new integer to the top of the stack */
17
public void
push(
int
value) {
18
if
(size >= elements.length) {
19
int
[] temp =
new int
[elements.length *
2
];
20 System.arraycopy(elements,
0
, temp,
0
, elements.length);
21 elements = temp;
22 }
23
24 elements[size++] = value;
25 }
26
27
double the capacity
add to stack
/** Return and remove the top element from the stack */
28
public int
pop() {
29
return
elements[——size];
30 }
31
32
/** Return the top element from the stack */
33
public int
peek() {
34
return
elements[size -
1
];
35 }
36
37
/** Test whether the stack is empty */
38
public boolean
empty() {
39
return
size ==
0
;
40 }
41
42
/** Return the number of elements in the stack */
43
public int
getSize() {
44
return
size;
45 }
46 }
You can define utility classes that contain static methods and static data.
Key
Point
Listing 3.3, GuessBirthday.java, and Listing 7.6, GuessBirthdayUsingArray.java, presented
two programs for guessing birthdays. Both programs use the same data developed with the
procedural paradigm. The majority of the code in these two programs is to define the five sets
of data. You cannot reuse the code in these two programs, because the code is in the
main
method. To make the code reusable, design a class to encapsulate the data, as defined in
Figure 10.13.
Note that
getValue
is defined as a static method because it is not dependent on a specific
object of the
GuessDate
class. The
GuessDate
class encapsulates
dates
as a private mem-
ber. The user of this class doesn't need to know how
dates
is implemented or even that the
dates
field exists in the class. All that the user needs to know is how to use this method to
access dates. Suppose this class is available. As shown in Section 3.4, there are five sets of
dates. Invoking
getValue(setNo, row, column)
returns the date at the specified row and
column in the given set. For example,
getValue(1, 0, 0)
returns
2
.