Stack<E>.withCapacity constructor
Stack<E>.withCapacity (
- int capacity, [
- E? defaultValue
Creates a Stack with the specified initial capacity.
A last-in-first-out (LIFO) stack implementation, mimicking Java's Stack.
This implementation extends Vector (represented as a List) and provides stack operations like push, pop, peek, and search. Elements are added and removed from the top of the stack.
Key Features:
- LIFO ordering: Last element added is first to be removed
- Dynamic sizing: Grows and shrinks as needed
- Vector-based: Built on top of a resizable array
- Thread-safe operations: All operations are atomic
Usage Examples:
final stack = Stack<String>();
// Push elements onto the stack
stack.push('first');
stack.push('second');
stack.push('third');
// Peek at the top element
print(stack.peek()); // 'third'
// Pop elements from the stack
print(stack.pop()); // 'third'
print(stack.pop()); // 'second'
// Check if empty
print(stack.empty()); // false
// Search for an element
print(stack.search('first')); // 1 (1-based position from top)
Implementation
Stack.withCapacity(int capacity, [E? defaultValue]) : _elements = List<E>.filled(capacity, defaultValue ?? null as E, growable: true), _defaultValue = defaultValue;