From 624527324fd25104bfa23fc03a9a7c449e8b374a Mon Sep 17 00:00:00 2001 From: roger ramos paredes <44221830+r3gor@users.noreply.github.com> Date: Mon, 2 Mar 2020 01:59:34 -0500 Subject: [PATCH] fix GenericStack.pop() and modify toString() 1. Call list[size] should return null (if list[size-1] is the last element of the stack), this does not happen because the pop() method does not actually eliminate any element. 2. When pop() is called, size should never be left with a negative value. --- Exercise_19/Exercise_19_01/GenericStack.java | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/Exercise_19/Exercise_19_01/GenericStack.java b/Exercise_19/Exercise_19_01/GenericStack.java index f22dadf1..1e0673cc 100644 --- a/Exercise_19/Exercise_19_01/GenericStack.java +++ b/Exercise_19/Exercise_19_01/GenericStack.java @@ -22,7 +22,12 @@ public void push(E o) { /** Return and remove the top element from the stack */ public E pop() { - E o = list[--size]; + if (--size < 0) + size = 0; + E o = list[size]; + E[] new_list = (E[]) new Object[list.length]; + System.arraycopy(list, 0, new_list, 0, size); + list = new_list; return o; } @@ -41,6 +46,15 @@ private void doubleList() { @Override // Override the toString array in the Object class public String toString() { - return "stack: " + list.toString(); + String s = "Stack: ["; + if (isEmpty()) + return s + "]"; + for (int i = 0; i < size; i++) { + if (i == size-1) + s += list[i].toString() + "]"; + else + s += list[i].toString() + ", "; + } + return s; } -} \ No newline at end of file +}