1. Why another data structure if we already have MutableList?
When you’ve just gotten comfortable with MutableList, it can feel like you found a universal Swiss Army knife. You want to store everything as a list: command history, a task queue, an action stack. And yes, you can—Kotlin doesn’t forbid it. But sometimes a list starts behaving like a suitcase without a handle: you can carry it, but it’s constantly awkward.
The problem usually shows up in two situations. First: you need to quickly add/take elements from the front (for example, “first in—first out”). Second: you need to quickly work with the last elements, like in an action history (“last action—undo”). In these cases, ArrayDeque is often easier to read and more honest in terms of meaning.
From Kotlin’s standard library perspective, ArrayDeque<T> is a double-ended queue: you can add and remove elements from both the front and the back. It’s implemented on top of a “resizable array” that grows as needed.
2. ArrayDeque, in plain terms: a double-ended queue
If you translate the term deque into everyday analogies, it’s something like “a queue with a door both in front and in back.” A regular store line works strictly on two ends: you join at the back, and you’re served from the front. And ArrayDeque is a queue where the cashier can also serve people from the other end (a weird store, but the data structure is happy).
What matters is that ArrayDeque in Kotlin covers two classic scenarios at once. If you use only the back for adding and the front for removing, that’s a FIFO queue. If you use only the back for both adding and removing, that’s a LIFO stack. And all of this is done with standard methods—no reinventing the wheel on top of MutableList.
Below is a mini diagram to make it stick visually:
flowchart LR
subgraph FIFO["FIFO queue"]
A1["addLast(x)"] --> A2["... queue ..."] --> A3["removeFirst()"]
end
subgraph LIFO["LIFO stack"]
B1["addLast(x)"] --> B2["... stack ..."] --> B3["removeLast()"]
end
3. Basic ArrayDeque operations
Before we “plug” ArrayDeque into our learning app, it’s important to master the very basics. With MutableList we’re used to add(...), removeAt(...), indexes, and lastIndex. In ArrayDeque the focus is different: we work with the front/back, not with indexes.
You can remember the main operations like this: addFirst/addLast means “put an element in,” removeFirst/removeLast means “take an element out and delete it,” and first()/last() means “peek without removing.” Kotlin documentation shows this directly with a small example.
Creating an ArrayDeque
import kotlin.collections.ArrayDeque
fun main() {
val empty = ArrayDeque<Int>()
println(empty) // []
val deque = ArrayDeque(listOf(1, 2, 3))
println(deque) // [1, 2, 3]
}
Notice a nice Kotlin-collections detail: even if a collection is stored in a val, you can still mutate it (the contents change, not the reference). This is a general principle for mutable collections.
Adding and peeking at the first/last element
import kotlin.collections.ArrayDeque
fun main() {
val d = ArrayDeque(listOf(1, 2, 3))
d.addFirst(0)
d.addLast(4)
println(d) // [0, 1, 2, 3, 4]
println(d.first()) // 0
println(d.last()) // 4
}
This snippet almost repeats the example from the official collections page, and that’s good: if an example is “canonical,” it’s easier for your brain to latch onto it.
Removing and checking for emptiness
Removal is where beginners most often “catch” an exception and then sadly stare at the stack trace. The thing is, removeFirst() and removeLast() assume an element exists. If the deque is empty, you’ll get an error.
So the key reflex is: before removing, check isNotEmpty() or isEmpty(). These functions exist on Kotlin collections and are constantly useful in defensive code.
import kotlin.collections.ArrayDeque
fun main() {
val d = ArrayDeque<Int>()
if (d.isNotEmpty()) {
println(d.removeFirst())
} else {
println("Deque is empty, nothing to remove") // Deque is empty, nothing to remove
}
}
4. A FIFO queue with ArrayDeque
A FIFO queue is one of the most natural real-life patterns: tasks arrive, and we process them in order. In programming, queues appear in “task scheduler” logic, “message processing queues,” “document printing,” “batch command processing.” Even if you’re not writing complex systems yet, a queue is a useful mental model.
With ArrayDeque, a FIFO queue is as simple as it gets: add to the back with addLast, take from the front with removeFirst. In other words, you’re telling the structure: “put the new one at the tail” and “serve the first one at the head.”
Here’s a short demo:
import kotlin.collections.ArrayDeque
fun main() {
val q = ArrayDeque<String>()
q.addLast("read file")
q.addLast("parse data")
q.addLast("build report")
println(q.removeFirst()) // read file
println(q.removeFirst()) // parse data
println(q) // [build report]
}
If you noticed, there isn’t a single index here. That’s not a “limitation,” it’s a “hint”: the structure makes your code closer to the intended meaning. If you implement a queue via list indexes, you’re already pretending you need a list, when in fact you need a queue.
5. A LIFO stack with ArrayDeque
A LIFO stack is another everyday logic: you stack plates, and you take the top one. In programming, a stack usually shows up wherever there is “history” and “rollback”: user action history, command history, nested calls, back navigation. We won’t dive into theoretical rabbit holes, but a practical undo scenario is very clear even for a beginner.
With ArrayDeque, you implement a stack like this: add to the back with addLast, and take from the back with removeLast. Reading-wise, it looks like “push on top” and “pop from top.”
import kotlin.collections.ArrayDeque
fun main() {
val stack = ArrayDeque<String>()
stack.addLast("open settings")
stack.addLast("change theme")
stack.addLast("save")
println(stack.removeLast()) // save
println(stack.removeLast()) // change theme
println(stack) // [open settings]
}
Yes, you could do the same with MutableList and removeAt(lastIndex). But ArrayDeque wins here because the method names describe the intent: “remove from the end” is exactly what you’re doing.
6. ArrayDeque in a CLI app: add-history and undo
Now for the interesting part: let’s carefully “land” ArrayDeque in our practical project (a console expense/notes tracker). In previous days, we already built commands like add, list, remove and learned to update collections without breaking iteration. Today we’ll add a small but very real feature: undo the last add.
Let’s be honest upfront: we’ll keep undo simple. It will roll back only the most recent add operations (and only in the order they happened). This isn’t production Git; it’s a learning example. The point is to feel why a “history stack” is an ArrayDeque.
Mini data model
Since classes and data class are still ahead of us, we’ll store expenses as Pair<String, Int>, where first is the category and second is the amount. We already know this from previous days on Pair/Triple.
typealias Expense = Pair<String, Int> // if typealias hasn't been covered in your track yet, just remove this line
If typealias hasn’t been covered in your cohort yet, no problem: you can write Pair<String, Int> directly in code. The meaning doesn’t change.
Add-history stack
The idea is: when the user enters the add command, we add the record to the expenses list and in parallel push the same record onto the history stack. When the user enters undo, we pop the last record from history and remove the last record from the expenses list.
import kotlin.collections.ArrayDeque
fun main() {
val expenses = mutableListOf<Pair<String, Int>>()
val history = ArrayDeque<Pair<String, Int>>() // stack: last add is on top
expenses.add("food" to 250)
history.addLast("food" to 250)
expenses.add("taxi" to 600)
history.addLast("taxi" to 600)
println(expenses) // [(food, 250), (taxi, 600)]
}
Implementing undo
Now we’ll implement a “naive but clear” undo: it works only if there’s something to roll back. So we use the isNotEmpty() check—the small safety fuse that prevents removing from an empty structure.
import kotlin.collections.ArrayDeque
fun undoLastAdd(
expenses: MutableList<Pair<String, Int>>,
history: ArrayDeque<Pair<String, Int>>
) {
if (history.isEmpty()) {
println("Nothing to undo") // Nothing to undo
return
}
history.removeLast()
expenses.removeLast()
println("Last add has been undone") // Last add has been undone
}
There’s a subtle point here: removeLast() on MutableList removes the last element. We assume history and expenses are synchronized (we always added to both as a pair). That’s a fine learning model. In a real project, you’d protect this more strongly, but our goal for now is to understand the structure.
Mini command loop: add and undo
Let’s assemble a small “command loop” snippet. It doesn’t claim to be perfect, but it shows where ArrayDeque fits conceptually.
import kotlin.collections.ArrayDeque
fun main() {
val expenses = mutableListOf<Pair<String, Int>>()
val history = ArrayDeque<Pair<String, Int>>()
while (true) {
val line = readln().trim()
if (line == "exit") break
val parts = line.split(" ")
when (parts[0]) {
"add" -> {
val cat = parts.getOrNull(1) ?: continue
val amount = parts.getOrNull(2)?.toIntOrNull() ?: continue
val e = cat to amount
expenses.add(e)
history.addLast(e)
println("OK") // OK
}
"undo" -> {
if (history.isNotEmpty()) {
history.removeLast()
expenses.removeLast()
println("UNDO") // UNDO
} else {
println("Nothing to undo") // Nothing to undo
}
}
"list" -> println(expenses)
else -> println("Unknown command")
}
}
}
Yes, there are places you could improve (input validation, error messages, supporting remove and keeping history consistent). But that’s fine: we introduced ArrayDeque as a tool without turning the example into a “console mega-app.” In learning code, it’s useful to stop in time—otherwise it becomes hard to understand which part is responsible for what.
7. When ArrayDeque is not a good fit
It’s tempting to fall in love with a new structure and start stuffing it everywhere, but it’s better to set emotions aside and switch into engineering mode. ArrayDeque is great when you truly work with the ends of the collection. If you need random access (“give me the element at index i”), if you need to sort constantly, if you need key-based lookup—that’s the territory of List/Map and collection operations we covered earlier.
It’s also important to remember that ArrayDeque is a mutable structure. It’s perfect for “accumulate and consume” scenarios, but if you build pipelines in the style of “don’t mutate the input data” (like in our discussions about Sequence and readable chains), then ArrayDeque more often acts as a “working container” rather than a “computation result.”
If you want a simple “mental filter,” keep this table in mind:
| What you need to do most often | Candidate tool | Why |
|---|---|---|
| Add/remove from the front and back | |
Methods express the intent directly (addFirst/removeLast, etc.) |
| Work by indexes, keep order, sort | |
This is the “native home” of indexes and sorting |
| Key-based access and accumulating “key → value” | |
Key lookup is the map’s primary contract |
| Produce reports and totals without mutation | |
Pure computations are easier to read |
Where else ArrayDeque shows up often
To broaden your horizons a bit (without any obligation to “go grind competitive programming”), it’s useful to know that queues and deques often appear in graph traversal and pathfinding algorithms. In Kotlin materials this even pops up in an Advent of Code walkthrough, where ArrayDeque is mentioned as a convenient queue.
This doesn’t mean you urgently need to learn graphs. It means that even today you’re picking up a tool that’s useful both in “regular application development” (action history, task processing) and in more algorithmic tasks if you get there.
8. Common mistakes when working with ArrayDeque
Error No. 1: removing from an empty deque without checking.
removeFirst() and removeLast() assume the element exists. If the deque is empty, you’ll get an exception. The fix is simple: before removing, check isNotEmpty() or isEmpty(). This pattern is universal for Kotlin collections and regularly saves you from “crashing out of nowhere.”
Error No. 2: mixing up a queue and a stack in the same structure.
A very common logical confusion: you add with addLast and remove with removeLast, thinking you built FIFO, but you actually built LIFO. A simple self-check helps: FIFO is always “add to tail—take from head,” i.e., addLast + removeFirst. LIFO is always “push on top—pop from top,” i.e., addLast + removeLast.
Error No. 3: trying to use ArrayDeque like a list with indexes.
When your hand reaches for something like “give me deque[3],” that’s a signal you picked the wrong structure. ArrayDeque is about the ends, not about random access. If you need index access, go back to List/MutableList—the code will be more honest and easier to read.
Error No. 4: storing history in ArrayDeque but not keeping it in sync with the main data.
In the undo example, we kept expenses and history synchronized. If in real code you sometimes add an expense to expenses but forget to add it to history, then undo will start rolling back “the wrong thing.” That’s not an ArrayDeque bug—it’s a data discipline bug. The fix is to apply changes to the main state and history next to each other, in the same code branch, as a single action.
Error No. 5: turning ArrayDeque into “just another collection, just in case.”
Sometimes people add ArrayDeque “for the future,” even though the program uses neither a queue nor a stack. As a result, you get extra state that you have to maintain. A good criterion: if you can’t explain in one sentence where the structure’s “front” and “back” are in your logic, you probably don’t need it yet.
GO TO FULL VERSION