Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package prep_27_stack;
- import java.util.ArrayList;
- import java.util.NoSuchElementException;
- public class ArrayListStack implements StackI {
- private ArrayList<Object> stack;
- /**
- * Constructs an empty stack.
- */
- public ArrayListStack() {
- stack = new ArrayList<Object>();
- }
- /**
- * Adds an element to the top of the stack.
- *
- * @param element the element to add
- */
- @Override
- public void push(Object element) {
- stack.add(element);
- }
- /**
- * Removes the element from the top of the stack.
- *
- * @return the removed element
- */
- @Override
- public Object pop() {
- if (stack.size() - 1 < 0) {
- throw new NoSuchElementException();
- }
- Object element = stack.get(stack.size() - 1);
- stack.remove(stack.size() - 1);
- return element;
- }
- /**
- * Returns the element from the top of the stack. The stack is unchanged
- *
- * @return the element from the top of the stack
- */
- @Override
- public Object peek() {
- if (stack.size() - 1 < 0) {
- throw new NoSuchElementException();
- }
- Object element = stack.get(stack.size() - 1);
- return element;
- }
- /**
- * Checks whether this stack is empty.
- *
- * @return true if the stack is empty
- */
- @Override
- public boolean isEmpty() {
- if (stack.size() > 0) {
- return false;
- } else {
- return true;
- }
- }
- /**
- * The number of elements on the stack.
- *
- * @return the number of elements on the stack
- */
- @Override
- public int size() {
- return stack.size();
- }
- }
Add Comment
Please, Sign In to add comment