Case Study: A Custom Stack Class

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.

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.

原文链接:Case Study: A Custom Stack Class

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
Every day is beautiful if you choose to see it.
如果你愿意去发现,其实每一天都很美
评论 抢沙发

请登录后发表评论

    暂无评论内容