0

I am new at java and I am trying to write an array Stack now I want to avoid loitering in pop () function,

public class Stack {
private int[] s;
private int N=0;

public Stack(int capacity)
{
    s= new int [capacity];
}

public boolean IsEmpty ()
{
    return N==0;
}

public void push (int x)
{
    s[N++]=x;
}

public int pop ()
{
    int x=s[--N];
    s[N]=null;
    return x;
}

when it decrements that value in, there is still pointer to the element that has been took off the stack now I tried to set the removed item to null but the compiler gives me exception

what can I do in order to delete the pointer of the removed item?!

3
  • 1
    Which pointer? You are working with primitives here (int), not with objects Commented Feb 20, 2013 at 18:40
  • You should just keep a index of your array representing the top of the stack. Which I think is what you are trying to do with N. Commented Feb 20, 2013 at 18:41
  • You can't set a primitive, such as int, to null. Only descendants of Object can be null. It should suffice to only decrement your counter (N) in pop(), and be sure to correctly set the last stack element in push(). Commented Feb 20, 2013 at 18:48

3 Answers 3

1

Your array stores int values which are not references, and null is not a valid value for type int. The trick your are using is handy when you deal with values of reference types, such as Object or String. In your case you can assign 0 or -1 or Integer.MIN_VALUE to the empty elements, but not null. Moreover, I think in your case you could just leave value as is:

public int pop ()
{
    return s [--N];
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use an ArrayList instead of an array. There you can remove objects at specified position, which will be always the last, in case of a stack.

Comments

0

Arrays of primitives store values, not pointers, so you there is no memory leak you have to worry about.

This line:

s[N]=null;

is not required in java (and does not compile anyway because null is not a valid primitive value).

Java ain't C.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.