I want to know why the push method in Stack has a return type? I checked Oracles documentation, but only the return type is mentioned. Can anyone tell me why the return type is required?
You are not required to use the return type. You can simply ignore it, and this is the most likely use case. However it could be useful if you want to create the object being pushed, push it to the stack, and maintain a reference to it, all with one line of code.
MyObject newOne = stk.push(new MyOjbect());
The top of the Stack now contains a reference to the newly created MyObject instance, but you also have a reference to it in the scope in which it was pushed in case you need it to perform further operations without removing it from the stack.
If you're extremely concerned with overhead, you could simply use the addElement() method, which does the exact same thing with less method overhead and no return value. If you take a look at the Java source code, which comes bundled with your Java SDK, you can see that push() is calling addElement() under the hood:
public E push(E item) {
addElement(item);
return 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