Generic Classes

This example demonstrates the use of generics to create a stack data structure.

class Stack<T> {
  List<T> _elements = [];

  void push(T element) {
    _elements.add(element);
    print('Pushed: $element');
  }

  T pop() {
    if (_elements.isEmpty) {
      throw Exception('Stack is empty');
    }
    var element = _elements.removeLast();
    print('Popped: $element');
    return element;
  }

  bool get isEmpty => _elements.isEmpty;
}

void main() {
  var intStack = Stack<int>();
  intStack.push(1);
  intStack.push(2);
  intStack.pop();

  var stringStack = Stack<String>();
  stringStack.push('Hello');
  stringStack.push('World');
  print('Popped from string stack: ${stringStack.pop()}');
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *