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

MABD
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. Disregard other classes if you want.

OK, assume that we have this in the main method

Stack<Object> s = new Stack<Object>();

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.

If you wonder what synchronized do, it locks an object, in this case, a method, from any shared resources. This is usually happening because of multi-threading stuff.

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() witch 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

--

--