Stack

Table of contents
  1. Usage
  2. Creation
  3. Modification
    1. Adding elements
    2. Retrieving elements
    3. Sorting / shuffling

Usage

The Stack utility class is a kotlin implementation of the common stack collection. The stack may become useful for many board game applications like card stacks, money stacks, etc.

Creation

The stack can be created with initial elements as a constructor parameter, either as collection or varargs, or as an empty stack with no constructor parameters. The elements get added from the tail to the head such that the first element in the collection will be popped first and the last element gets the highest index.

val emptyStack: Stack<String> = Stack()
val collectionStack: Stack<String> = Stack(listOf("ONE", "SIX", "TEN"))
val varargsStack: Stack<String> = Stack("ONE", "SIX", "TEN")

Modification

Adding and removing elements is only available for the topmost element as the stack represents a LIFO queue.

Adding elements

Elements get added by calling push for one element or pushAll for multiple elements. For multiple elements, they get pushed one by one from the first to the last element in the given collection.

Retrieving elements

Elements get removed by calling pop. This removes the topmost element from the stack and returns it. popAll can be used to pop all elements or, by specifying parameter n, the given number of elements.

peek returns the topmost element without removing it. peekAll works respectively.

The first index of any element in the stack can be obtained by calling indexOf. This returns -1 if the element is not contained in the stack.

The stack can be cleared by calling clear.

Note that pop/peek throws a NoSuchElementException if the stack is empty. Use popOrNull/peekOrNull for safe access or check stack’s size or call isEmpty / isNotEmpty.

Sorting / shuffling

The stack can be sorted by calling sort and shuffled by calling shuffle.