3
\$\begingroup\$

My understanding is that Stack possesses LIFO property. And, based upon that I have written the following program:

// This is a sample program to demonstrate push and pop// functionality in Stack in Java.package collections;public class Stack_Array {    private static final int capacity = 3;    int[] arr = new int[capacity];    int top = -1;    public void push(int pushedElement) {        if(top >= capacity) {            System.out.println("StackOverflow !!");        } else {            top++;            arr[top] = pushedElement;        }    }    public void pop() {        if(top>=0) {            top--;                  } else {            System.out.println("Stack underflow !!");        }    }    public void printStack() {        System.out.println("Elements in Stack are: ");        for(int i = top; i >=0; i--) {            System.out.println(arr[i]);        }    }    public static void main(String[] args) {        Stack_Array s1 = new Stack_Array();        s1.push(23);        s1.push(21);        s1.push(14);        s1.pop();        s1.printStack();    }}

Please let me know if it is the correct approach. Or, is there a better way to implement the same

Mathieu Guindon's user avatar
Mathieu Guindon
75.6k18 gold badges195 silver badges469 bronze badges
askedOct 31, 2016 at 1:22
meallhour's user avatar
\$\endgroup\$

1 Answer1

5
\$\begingroup\$

I like the consistency of your braces and indentation - well done!

The nameStack_Array should beStackArray, since asmember names arecamelCase,type names ought to bePascalCase, notUpper_Snake_Case.


You'll want to implement aconstructor so that thecapacity of the object can be parameterized, and then the calling code can look like this:

StackArray foo = new StackArray(42);foo.push(bar);

The underlyingcapacity static field would need to be changed a bit though; you'll want it to be aninstance field, so that eachobject can have its own independent value. I'd keep itfinal though, because it's not a value you want to be able to modify during the lifetime of an instance - beyond theconstructor, nothing should be allowed to modify that value.


You'll want to throw an appropriateexception inexceptional situations:

if(top >= capacity) {    System.out.println("StackOverflow !!");

AStack is adata structure; other code will rely on its correct behavior, andexpect a number of errors to occur in certain specific situations - for example when the caller attempts topush an element into an instance that already contains as many items as it can hold.

That said, I'd prefer aStack implementation that simply increases its capacity as items are pushed. In any case, printing "StackOverflow !!" isn't appropriate. Making the method return abool that the calling code can evaluate to determine whether the push/pull succeeded or not, would be a better alternative if youreally want a fixed capacity.


Printing to the console isn't the job of a data structure,printStack should be replaced by a method thatreturns a new data structure that contains acopy of the internal array. Such atoArray method would leave it up to the calling code to decide whether they want to print the items to the console, or dump them into a log file, or whatever.


Your implementation is pretty bare-bones, you'll want to look at thejava.util.Stack<E> members and possibly dig into generics. The C#System.Collections.Generics.Stack<T> class could also be an inspiration.

Thepop method would be expected toreturn the popped item. Apeek method is missing, to "peek" at the next item without popping it out of the stack.


Other observations

Betweenpush andpop, the two have anif conditional, but one is no-op in the positive branch, while the other is no-op in the negative branch (/else block). It would be better to decide whether you test for the error condition[to throw an error and fail early] or if you test for the success condition[and throw an error in theelse block] - it's usually better tofail early and reduce the indentation level:

public void foo() {    if ({error condition}) {        throw new SomeException();    }    doSomething();}

Watch the spacing on either side of comparison operators:

for(int i = top; i >=0; i--) {

Give it the same whitespace as for the= assignment operator:

for(int i = top; i >= 0; i--) {
answeredOct 31, 2016 at 3:00
Mathieu Guindon's user avatar
\$\endgroup\$

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.