Stack<E>.from constructor

Stack<E>.from(
  1. Iterable<E> iterable, [
  2. E? defaultValue
])

Creates a Stack from an iterable.

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.from(Iterable<E> iterable, [E? defaultValue]) : _elements = List<E>.from(iterable), _defaultValue = defaultValue;