-2

My question is simple. If I have a data structure like a stack in java and add some elements, then I create other stack and equals to first stack using = operator (Example 1) instead empty the first one using while loop (Example 2). If i try to use the second stack in other scope, Can I lost the data if first stack is empty?

Stack<String> stack=new Stack<>();
Stack<String> stack_aux=new Stack<>();
stack.push("Hola");
stack.push("Mundo");
stack.push("in Java");

Example 1

stack_aux=stack;

Example 2

while(!stack.isEmpty()){
        stack_aux.push(stack.pop());
}
Ale
  • 226
  • 1
  • 9
  • 17
  • 1
    If you do `stack_aux=stack;` you are letting the variable `stack_aux` point to the existing stack, not creating a duplicate of the stack. – Adriaan Koster Nov 01 '17 at 15:11

2 Answers2

1

To copy a stack to another stack, you need to do something like:

stack_aux.addAll(stack);

You can't just use = in your Example 1

Your Example 2 will work just fine.

Edit:

Actually a better way is to use the clone() method:

stack_aux = (Stack<String>) stack.clone();
achAmháin
  • 4,176
  • 4
  • 17
  • 40
  • You should probably explain that `addAll` will only work in specific circumstances as it does not perform a deep copy. You should probably also explain what "deep copy" means or point to somewhere that provides a good explanation. – D.B. Nov 01 '17 at 15:16
  • @D.B. yes - I guess my edit was supposed to say 'basically ignore the above and use the `clone()` method :) – achAmháin Nov 01 '17 at 15:25
1

When we interview new Java programmers, this is one of the basic questions we ask.

What is the difference between =, ==, and equals() in Java?

Part of this is already answered in several other SO posts, for example this. One of the Java basics not explicitly covered is that the = sign in Java is the assignment operator. That is, when you say

stack_aux=stack;

You are assigning the value of stack into the variable stack_aux.

When you do this, the value of stack_aux will be lost if you don't hold a copy of it in some other variable. This will happen regardless of whether stack is empty or not.

When you do this:

while(!stack.isEmpty()){
        stack_aux.push(stack.pop());
}

You will push the values of stack on top of stack_aux when stack is not empty.

Michael Peacock
  • 2,011
  • 1
  • 11
  • 14