0

Only the first call of display() works as intended. After the first call, tmpStack is empty and therefore the second call of display() won't print anything. How can I avoid this?

public static void main(String[] args) {

        s.display(sortedStack);
        s.display(sortedStack);
}

public void display(Stack<Integer> stackToDisplay){

    Stack<Integer> tmpStack = stackToDisplay;
    while(!tmpStack.isEmpty()){

        System.out.println(tmpStack.pop());
    }
}
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
Punit
  • 69
  • 1
  • 7

2 Answers2

1

Two options come to my mind.

Option 1:

If you don't want to lose your stack, don't pop the elements - just iterate though your stack:

public void display(Stack<Integer> stackToDisplay){

    Stack<Integer> tmpStack = stackToDisplay;

    for(Integer element : stackToDisplay) {
        System.out.println(element);
    }
}

The reason why the stack is empty after the first call is because it gets passed as reference and therefore any changes made in display() will have an effect on your real object.

Here is another way to iterate:

    Iterator<Integer> iter = tmpStack.iterator();    
    while (iter.hasNext()){
        System.out.println(iter.next());
    }

Option 2:

If you don't want this behavior at you could create a copy of your object - but I don't think that this is necessary in your case. A copy would only be necessary if you'd like to have two different Stacks later on. For that take a look at this question where you can find out how that works. Note that copying objects is always slower than passing references.

Community
  • 1
  • 1
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
  • @Punit I'm glad I could help. You can accept my answer by clicking below the up- and downvote buttons so others can see your question has been answered. – Stefan Falk Aug 21 '14 at 10:28
  • It needs 15 reputations to do so. As I'm new here I haven't reached those numbers. Will do that for sure once I reach that number. – Punit Aug 21 '14 at 17:54
-1

what behavior do you want?

I typically do something like this:

public void display(Stack<Integer> stackToDisplay)
{
    Stack<Integer> tmpStack = stackToDisplay;
    if(!tmpStack.isEmpty())
    {  
        while(!tmpStack.isEmpty())
        {
            System.out.println(tmpStack.pop());
        }
    }
    else
    {
        System.out.println("Stack is empty");
    }
}

Although, you can put anything you want in the else-block.

hopes this helps.

thurizas
  • 2,473
  • 1
  • 14
  • 15
  • Pretty sure the OP's issue is that their display function is emptying the stack (and they don't want that to happen), not that it prints nothing when given an empty stack. – nobody Aug 20 '14 at 23:54
  • @thurizas This is not working as this solution pops all elements in stack in first call itself. Solutions by Stefan Falk works as intended. – Punit Aug 21 '14 at 05:44