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(...)
?
push() return the object you are pushing. s. add() always return true.
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).
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.
An element can be added into the stack by using the java. util. Stack. push() method.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With