LoganBlackisle

ArrayListStack

Jun 18th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. package prep_27_stack;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.NoSuchElementException;
  5.  
  6. public class ArrayListStack implements StackI {
  7. private ArrayList<Object> stack;
  8.  
  9. /**
  10. * Constructs an empty stack.
  11. */
  12. public ArrayListStack() {
  13. stack = new ArrayList<Object>();
  14. }
  15.  
  16. /**
  17. * Adds an element to the top of the stack.
  18. *
  19. * @param element the element to add
  20. */
  21. @Override
  22. public void push(Object element) {
  23. stack.add(element);
  24. }
  25.  
  26. /**
  27. * Removes the element from the top of the stack.
  28. *
  29. * @return the removed element
  30. */
  31. @Override
  32. public Object pop() {
  33. if (stack.size() - 1 < 0) {
  34. throw new NoSuchElementException();
  35. }
  36. Object element = stack.get(stack.size() - 1);
  37. stack.remove(stack.size() - 1);
  38. return element;
  39. }
  40.  
  41. /**
  42. * Returns the element from the top of the stack. The stack is unchanged
  43. *
  44. * @return the element from the top of the stack
  45. */
  46. @Override
  47. public Object peek() {
  48. if (stack.size() - 1 < 0) {
  49. throw new NoSuchElementException();
  50. }
  51. Object element = stack.get(stack.size() - 1);
  52. return element;
  53. }
  54.  
  55. /**
  56. * Checks whether this stack is empty.
  57. *
  58. * @return true if the stack is empty
  59. */
  60. @Override
  61. public boolean isEmpty() {
  62. if (stack.size() > 0) {
  63. return false;
  64. } else {
  65. return true;
  66. }
  67. }
  68.  
  69. /**
  70. * The number of elements on the stack.
  71. *
  72. * @return the number of elements on the stack
  73. */
  74. @Override
  75. public int size() {
  76. return stack.size();
  77. }
  78. }
Add Comment
Please, Sign In to add comment