Koray Tugay
Koray Tugay

Reputation: 23780

How Java keeps reference to a Stack?

Code:

    Stack<Integer> firstStack = new Stack<Integer>();
    Stack<Integer> secondStack = firstStack;

    firstStack.push(1);
    firstStack.push(2);

    secondStack.pop();
    System.out.println(firstStack.pop());

My question is, if firstStack references the last item in the Stack and secondStack also references this item, when I pop from the secondStack, the firstStack should keep referencing the ( previous ) last item( which is 2 ). How come the reference of the firstStack changes to the first item as well? ( by first item I mean: 1 )

Upvotes: 2

Views: 147

Answers (4)

rai.skumar
rai.skumar

Reputation: 10667

Actually stack in java is implemented using Vector class.

Vector class has following attributes ( you can cross check by looking at implementation of Vector class)

   protected Object elementData[];
   protected int elementCount;
   protected int capacityIncrement;

So internally it stores data in an array and also keeps track of increment and count using other 2 clas attributes. So internally your firstStack and secondStack references point to the same elementData, elementCount and capacityIncrement attributes. Hence you get consistent results.

Upvotes: 1

Ajinkya
Ajinkya

Reputation: 22710

firstStack and secondStack are just reference to actual Stack object so even you perform pop/push on any of this you are updating the same Stack object.

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

No. Here Stack object is one and two references firstStack and secondStack both referring the same Stack Object. Any operation though any reference of this will effect on same object as both are referring same Object.

Stack<Integer> secondStack = firstStack;

This is not new Object creation and secondStack will refer what firstStack is referring.

Upvotes: 0

Both firstStack and secondStack refer to the stack itself, not the last object in the stack.

When you do

Stack<Integer> secondStack = firstStack;

you're saying: Take the stack object that firstStack refers to, and let secondStack refer to the same object. No copying of the stack is done, or similar.

Thus, if you pop from secondStack, you also pop from firstStack.

Upvotes: 7

Related Questions