Case Study: A Custom Stack Class

Paul Ngugi - Jun 10 - - Dev Community

This section designs a stack class for holding objects. This section 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 the program below. The UML diagram for the class is shown in Figure below.

Image description

Image description

An array list is created to store the elements in the stack (line 5). The isEmpty() method (lines 7–9) returns list.isEmpty(). The getSize() method (lines 11–13) returns list.size(). The peek() method (lines 15–17) retrieves 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 19–23) removes the top element from the stack and returns it. The push(Object element) method (lines 25–27) adds the specified element to the stack. The toString() method (lines 29–32) defined in the Object class is overridden to display the contents of the stack by invoking list.toString(). The toString() method implemented in ArrayList returns a string representation of all the elements in an array list.

In the program above, MyStack contains ArrayList. The relationship between MyStack and ArrayList is composition. While inheritance models an is-a relationship, composition models a has-a relationship. You could also implement MyStack as a subclass of ArrayList. Using composition is better, however, because it enables you to define a completely new stack class without inheriting the unnecessary and inappropriate methods from ArrayList.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .