Stack .add() or .push()???

MABD-Dev
2 min readFeb 22, 2020

To know what is the difference between them and how they work, we need to take a look at there holder classes.

Keep in mind that the Stack class extends the Vector class, we are going to need that later

OK, let’s say we have this piece of code in our project:

Stack<Object> s = new Stack<Object>();
s.push(new Object());
s.add(new Object());
// What is the difference?

s.push();

It calls the push method in the Stack class, which looks like this…

Stack Class

It then calls public addElement() in the Vector class and returns the item that we just pushed. To be able to do this for example

Object obj = s.push(new Object());
Image 1 : in Vector Class

As you can see, it calls another method in the Vector Class.

Synchronized here has to do with threading stuff. A topic for later

Image 2 : in Vector Class

Finally, it increases the size of the stack and pushes the element.

s.add();

It calls add() in the Stack Class,

Image 3 : in Vector Class

does this look familiar ???

Yes, it is.

This is the same as addElement() that s.push() calls, except it is always returning true.

It then calls add() method in the Vector Class. ‘Image 2’

To Conclude

s.push() -> public addElement() -> private add()always

but

s.add() -> public add() -> private add()

This is just a method call … Both ways they lead to the call of the private method .add() which add the element to the stack

The only difference between these calls is the return values.

s.push() return the object you are pushing.

s.add() always return true.

Thanks for reading

--

--