科特林 1.3.70介绍了kotlin.collections.ArrayDeque https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-deque/类,它既充当队列and堆栈,如 Java 的堆栈java.util.Deque https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html(Deque 意思是“双端队列”)。它是出于多平台的需要而创建的ArrayDeque
执行。
val stack = ArrayDeque(listOf(1, 2, 3)) // stack: [1, 2, 3]
stack.addLast(0) // stack: [1, 2, 3, 0] (push)
val value = stack.removeLast() // value: 0, stack: [1, 2, 3] (pop)
请注意,如果ArrayDeque
当你打电话时是空的removeFirst https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-deque/remove-first.html or removeLast https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-deque/remove-last.html,它会抛出一个kotlin.NoSuchElementException https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-no-such-element-exception/index.html#kotlin.NoSuchElementException。如果您不想每次需要访问双端队列时都检查它的大小,那么您应该使用removeFirstOrNull https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-deque/remove-first-or-null.html and removeLastOrNull https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-deque/remove-last-or-null.html功能。
可选片段
ArrayDeque
构造函数:
inline fun <T> arrayDequeOf(vararg elements: T) = ArrayDeque(elements.toList())
// ...
val stack = arrayDequeOf(1, 2, 3)
Stack
-like ArrayDeque
calls:
inline fun <T> ArrayDeque<T>.push(element: T) = addLast(element) // returns Unit
inline fun <T> ArrayDeque<T>.pop() = removeLastOrNull() // returns T?