Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stack push() vs add()

I am trying to use Stack, but I am slightly confused by the terminology.

I find that Stack class has only push(E e) as per Java doc.

And has add(E e) and addAll(Collection<? extends E> c) as a inherited method from Vector class.

Do they have the same functionality or is it better to use push(...) to insert elements to the Stack object.

In other words, will I encounter any issues if I use add(...) instead of push(...)?

like image 941
Kalyanaraman Santhanam Avatar asked Apr 13 '13 15:04

Kalyanaraman Santhanam


People also ask

What is the difference between push and add in stack?

push() return the object you are pushing. s. add() always return true.

Can the Add method used in stack?

The add(int, Object) method of Stack Class inserts an element at a specified index in the Stack. It shifts the element currently at that position (if any) and any subsequent elements to the right (will change their indices by adding one).

What is stack push in Java?

Stack push() Method in Java push(E element) method is used to push an element into the Stack. The element gets pushed onto the top of the Stack. Syntax: STACK.push(E element) Parameters: The method accepts one parameter element of type Stack and refers to the element to be pushed into the stack.

How do you add to a stack Java?

An element can be added into the stack by using the java. util. Stack. push() method.


2 Answers

Kalyanaraman Santhanam:

Edit: Will I encounter any issues if I use add(...) instead of push(...)?

Definitly, you will not encounter any issues, because add is part of List interface as well as the Stack, but you should to notice the further readability of your code and your intentions in it by other programmers. push method will give them a clue that they're using the Stack object, they will know certantly what to expect from. Also notice that push has different return value than add (the former has "pushed object" type and the latter just a boolean response)

like image 193
rook Avatar answered Sep 21 '22 01:09

rook


They are the same.

From the JavaDoc:

Pushes an item onto the top of this stack. This has exactly the same effect as:

addElement(item) 
like image 40
Frank Avatar answered Sep 20 '22 01:09

Frank