"Case Study: The StackOfIntegers Class," in §7.17, presented a stack class for storing int values. This section introduces a stack class to store objects. Recall that a stack is a data structure that holds objects in a last-in first-out fashion. You can use an ArrayList to implement Stack , as shown in Listing 9.8. The UML diagram for the class is shown in Figure 9.8.
1 public class MyStack { 2 private java.util.ArrayList list = new java.util.ArrayList(); 3 4 public boolean isEmpty() { 5 return list.isEmpty(); 6 } 7 8 public int getSize() { 9 return list. size (); 10 } 11 12 public Object peek() { 13 return list.get(getSize() - 1 ); 14 } 15 16 public Object pop() { 17 Object o = list.get(getSize() - 1 ); 18 list.remove(getSize() - 1 ); 19 return o; 20 } 21 22 public Object push(Object o) { 23 list.add(o); 24 return o; 25 } 26 27 public int search(Object o) { 28 return list.lastIndexOf(o); 29 } 30 31 /** Override the toString in the Object class */ 32 public String toString() { 33 return "stack: " + list.toString(); 34 } 35 } |
An array list is created to store the elements in the stack (line 2). The isEmpty() method (lines 4 “6) returns list.isEmpty() . The getSize() method (lines 8 “10) returns list.size() . The peek() method (lines 12 “14) looks at the element at the top of the stack without removing it. The end of the list is the top of the stack. The pop() method (lines 16 “20) removes the top element from the stack and returns it. The push(Object element) method (lines 22 “25) adds the specified element to the stack. The search(Object element) method checks whether the specified element is in the stack, and returns the index of first-matching element in the stack from the top by invoking list.lastIndexOf(o) . The toString() method defined in the Object class is overridden to display the contents of the stack by invoking list.toString() .
Note
In Listing 9.8, MyStack contains ArrayList . The relationship between MyStack and ArrayList is called composition . While inheritance models an is-a relationship , composition models a has-a relationship . You may also implement MyStack as a subclass of ArrayList . Relationships will be discussed in detail in Chapter 11, "Object-Oriented Design." |