0

This is not a pressing question, I'm just curious.

What is the difference between using push() to add another object to a Stack and using addElement() to add an object?

I have found elsewhere that there is no difference between things like push() and add(), since add() is inherited from Collections, but I'm still curious to find out if there is anything I should know.

Also, do they both have a similar return type?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
user2962515
  • 41
  • 1
  • 5
  • 6
    Read the javadocs... – Luiggi Mendoza Nov 06 '13 at 22:15
  • By the way, I won't recommend using `Stack` class since it inherits from `Vector` which [you shouldn't use in applications](http://stackoverflow.com/q/1386275/1065197), instead use [`Deque`](http://docs.oracle.com/javase/7/docs/api/java/util/Deque.html) which provides behavior of both Stack and Queue. – Luiggi Mendoza Nov 06 '13 at 22:18

3 Answers3

4

The inherited addElement method returns a boolean indicating success.

The push method ignores that returned boolean, calls addElement, and returns the item itself. Source code from the link:

public E push(E item) {
    addElement(item);

    return item;
}
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

addElement is part of Vector, which Stack inherits.

push is an actual Stack method.

yamafontes
  • 5,552
  • 1
  • 18
  • 18
0

This is caused by inheritance in java. addElement() is a method from the super class Vector extended by Stack.

You should see this (the inheritance tree in particular): http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

Fabio Carello
  • 1,062
  • 3
  • 12
  • 30