Java Reference
In-Depth Information
list.add(
2
);
list.add(
3
);
list.remove(
1
);
System.out.println(list);
This section designs a stack class for holding objects.
Key
Point
Section 10.9 presented a stack class for storing
int
values. This section introduces a stack
class to store objects. You can use an
ArrayList
to implement
Stack
, as shown in Listing
11.10. The UML diagram for the class is shown in Figure 11.4.
VideoNote
The
MyStack
class
MyStack
-list: ArrayList<Object>
A list to store elements.
+isEmpty(): boolean
+getSize(): int
+peek(): Object
+pop(): Object
+push(o: Object): void
Returns true if this stack is empty.
Returns the number of elements in this stack.
Returns the top element in this stack without removing it.
Returns and removes the top element in this stack.
Adds a new element to the top of this stack.
F
IGURE
11.4
The
MyStack
class encapsulates the stack storage and provides the operations
for manipulating the stack.
L
ISTING
11.10
MyStack.java
1
import
java.util.ArrayList;
2
3
public class
MyStack
{
private
ArrayList<Object> list =
new
ArrayList<Object>();
4
5
6
array list
public boolean
isEmpty()
{
stack empty?
7
return
list.isEmpty();
8 }
9
10
public int
getSize()
{
get stack size
11
return
list.size();
12 }
13
14
public
Object peek()
{
peek stack
15
return
list.get(getSize() -
1
);
16 }
17
18 {
19 Object o = list.get(getSize() -
1
);
20 list.remove(getSize() -
1
);
21
public
Object pop()
remove
return
o;
22 }
23
24
public void
push(Object o)
{
push
25 list.add(o);
26 }
27