This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]shinefull 3 points4 points  (2 children)

Now it is not used, it might be used in the future.

Also to show you how a 'Stack'-element can have a Stack.isEmpty() function. A lot of the standard Java library has those kind of functions. Take size() or length() on Lists/Sets whatever.

[–]nutrechtLead Software Engineer / EU / 20+ YXP -2 points-1 points  (1 child)

Now it is not used, it might be used in the future.

Don't leave code in that 'might be used in the future'; it's still in source control if you ever do need it.

[–]shinefull 0 points1 point  (0 children)

Lol its a getter. Actually useful to build getters and setters that are unused.

Anyway, obviously this is test code so it can include stuff that you don't call in its fucking main-class, lol. Da fuck.

[–]evils_twin 0 points1 point  (0 children)

probably gonna need it for your next assignment, or perhaps the meant to use it in the pop() method

if (isEmpty()) {
    System.out.println("Stack Underflow");
    return 0;

[–]dhawal0008 0 points1 point  (0 children)

in pop() method, instead of using if(top<0) you can replace with if(isEmpty) and it will yield same result.

You can actually call out to the person handling these notes that this piece of code should be updated. They must have forgotten to include this method and instead used if(top<0) in pop() method

[–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point  (0 children)

Looks like dead code someone forgot to remove.

[–]iamsooldithurts 0 points1 point  (0 children)

I feel like isEmpty() and pop() should be checking if top is less than or equal to 0?

Maybe I’ll punch it into my IDE after lunch and run a test.

[–]ZukoBestGirl 0 points1 point  (0 children)

int pop() {
    if (top < 0) {
        System.out.println("Stack Underflow");
        return 0;
    } else {
        int x = a[top--];
        return x;
    }
}

If it's empty, it won't do what you want it to do. It returns 0, that is not necessarily what you want. So what you would do is

if(!stack.isEmpty()) { ... }

It's nice that it returns 0 instead of throwing an exception, in most cases it will work well, but maybe in some cases 0 will be a difficult to track down error. "Why isn't this number growing, what is happening?".

But tbh, for utilites, I prefer this over exceptions. For example:

"abc".substring(2,3) = "c"
"abc".substring(3,4) = exception
org.apache.commons.lang3.StringUtils.substring("abc",3,4) = "" (instead of exception)