Why stack is using List java interface
This defining property of stacks is called "Last In, First Out" or LIFO
given the following piece of code
Stack<String> theStack = new Stack<String>();
theStack.push ("A");
theStack.push ("B");
theStack.push ("C");
theStack.remove (1); // removes B
print output
System.out.println(theStack);
outputs output
[A, C]
Since the Stack is part of the List interface, there is a way to delete ,
"hence it violates the LIFO property of the stack"
Is this purposefully designed in the Java Collection Framework?
This is useful in many cases if it Stack
is implemented List
: it means that it can be used wherever required List
.
But if you use it as a stack, then you are required to do intelligent stack-like operations on it, and that includes not randomly popping out of the middle.
This does not mean that this is a poor implementation of the LIFO queue, it simply means that you must be careful to use it in LIFO mode.
(However, a strong argument can be made for Stack.remove()
throwing away OperationNotSupportedException
.)
Not all collections created in java framework adhere to the algorithmic counting part there. Ex. A queue is a FIFO, but it is implemented by LinkedList (because a linked list implements the Queue interface), so you can do things that you don't expect to do in the queue (like removing an item from a specified position, zero insertion, etc.). If you want to create an API to strictly define algorithmic operations, then:
1. Create your own class and return them using Java classes 2. Be conscientious when you code and don't call unnecessary methods.