2

Its clearly specified that java.util.Stack is a LIFO stack implementation of List Interface.
One would naturally think since Stack follows a LIFO paradigm , it should throw UnsupportedOperationException when someone tries to invoke its add method which it inherited from List which in turn inherits from Collection.
method add is an optional operation . i.e implementations are not necessarily required to implement them and can rather just throw an UnsupportedOperationException on their invocation.
Stack should have naturally done so, since you can only add new elements in the last, since its a stack. I am surprised add(int index,E e) method actually works on Stack objects! defeats the purpose of Stack if you can add an element anywhere in it and not just the end

Sarabjeet
  • 264
  • 2
  • 17

1 Answers1

2

It extends Vector, and therefore supports operations such as get(int) and add(int,E). It is a known weird thing and is considered a design mistake by many. What you say about it defeating the purpose of a stack is true.

Community
  • 1
  • 1
keyser
  • 18,829
  • 16
  • 59
  • 101