List<T>
from System.Collections.Generic
does everything Stack<T>
does, and more -- they're based on the same underlying data structure. Under what conditions is it correct to choose Stack<T>
instead?
You would use stack if you had a need for a Last In First Out collection of items. A list will allow you to access it's items at any index.
We use stack or queue instead of arrays/lists when we want the elements in a specific order i.e. in the order we put them (queue) or in the reverse order (stack). Queues and stacks are dynamic while arrays are static. So when we require dynamic memory we use queue or stack over arrays.
A stack is an abstract data type that serves as a collection of elements with two principal operations which are push and pop. In contrast, a linked list is a linear collection of data elements whose order is not given by their location in memory. Thus, this is the main difference between stack and linked list.
Correctly implemented, an array-based stack or queue can be faster and more memory efficient than a linked list implementation.
You would use stack if you had a need for a Last In First Out collection of items. A list will allow you to access it's items at any index. There are a lot of other differences but I would say this is the most fundamental.
Update after your comment:
I would say that using Stack<T>
makes a statement about how you want this code to be used. It's always good to plan for the future, but if you have a need for Stack<T>
right now, and no compelling reason to use List<T>
then I would go with Stack<T>
why I would artificially limit myself to using Stack in new code
There's your answer - you should use Stack
when you have a need to enforce a contractual expectation that the data structure being used can only be operated on as a stack. Of course, the times you really want to do that are limited, but it's an important tool when appropriate.
For example, supposed the data being worked with doesn't make any sense unless the stack order is enforced. In those cases, you'd be opening yourself up to trouble if you made the data available as a list. By using a Stack
(or a Queue
, or any other order-sensitive structure) you can specify in your code exactly how the data is supposed to be used.
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