CodeGym /Courses /Kotlin SELF /Comparing arrays: why == is not suitable and when you nee...

Comparing arrays: why == is not suitable and when you need contentDeepEquals

Kotlin SELF
Level 23, Lesson 4
Available

1. Why arrays are compared differently

When you first encounter arrays, you want to think of them as “a list, just fixed-size.” And that is partly true. But arrays have a personality: they are a bit closer to the “metal,” they are often used as a compact container, and because of that in Kotlin (and on the JVM in general) they are compared differently than List.

Imagine we are evolving our console expense-tracking app (the one where we store expenses as “category–amount” pairs, sort them, take top-N, and build reports). Sometimes it is convenient for us to keep, for example, totals by day of the week in an IntArray—exactly 7 numbers: Mon…Sun. And then a practical question arises: “do two weekly snapshots match?”, “did the data change after recalculation?”, “did I break something in the logic?”.

And here comes the surprise: you write “well, I’ll just compare them with ==”—and you get a result that feels like it is mocking you.

Why == does not compare arrays element-by-element

In short and to the point: == for arrays does not do what you expect. In Kotlin, == means structural equality and calls equals() (with safe handling of null). But with arrays on the JVM, historically, their equals() behaves like “compare containers,” not “compare contents.” And Kotlin explicitly warns: for arrays, do not use ==/!= if you want to compare elements.

Intuitively it is like this: you compare two identical pizza boxes, but instead of asking “same toppings?” you ask “is this the same box from my fridge?”. In most cases the answer will be “no,” even if the inside is equally delicious.

Mini example: the == trap

fun main() {
    val a = arrayOf(1, 2, 3)
    val b = arrayOf(1, 2, 3)

    println(a == b)   // false (expected true? welcome aboard)
    println(a === b)  // false (these are definitely different arrays)
}

Why does this happen? Because a and b are two different arrays. == in this case does not perform an element-by-element comparison; essentially, it does not tell you “equal by content.”

At the same time, for many other types, == really does compare “by meaning,” and Kotlin clearly separates structural (==) and referential (===) equality. Arrays are just a special zone.

Comparison map: ==, ===, contentEquals, contentDeepEquals

To avoid keeping everything in your head as a mess, it helps to have a small table—like a road sign: “caution, arrays.”

What you write What it means Works for arrays? When to use
a == b
structural equality (equals) for arrays, not for comparing elements almost always for “regular” types and collections (List, Map)
a === b
referential equality (the same object) yes, but this is not about elements rare checks like “is this the same container?”
a.contentEquals(b)
element-by-element comparison of a flat array yes when the array is 1D: IntArray, Array<String>, …
a.contentDeepEquals(b)
“deep” comparison for nested arrays yes when arrays contain other arrays

The main takeaway of this lecture: if you want to compare arrays by data, use contentEquals/contentDeepEquals.

2. contentEquals() for flat arrays

When an array is flat (meaning its elements are not arrays), you almost always need contentEquals().

Example 1: Array<Int>

fun main() {
    val a = arrayOf(1, 2, 3)
    val b = arrayOf(1, 2, 3)

    println(a.contentEquals(b)) // true
}

Now this looks like a human conversation: “yes, the elements are the same and in the same order.”

Example 2: IntArray

In our “daily expense totals” tasks, it makes more sense to store them in an IntArray (this is a primitive array on the JVM; it is more memory-efficient). Kotlin provides types like IntArray, DoubleArray, etc.

fun main() {
    val week1 = intArrayOf(100, 0, 250, 0, 90, 500, 10)
    val week2 = intArrayOf(100, 0, 250, 0, 90, 500, 10)

    println(week1.contentEquals(week2)) // true
}

An important nuance: order matters

Just like with lists, content comparison takes order into account. That is logical: an array is a “sequence.” If you swapped days around, that is already a different value.

fun main() {
    val a = intArrayOf(1, 2, 3)
    val b = intArrayOf(3, 2, 1)

    println(a.contentEquals(b)) // false
}

How this looks in our app

Suppose you wrote a function that builds weekly expense totals by day (we are not building class-based architecture yet—just working with simple types and collections). And you want to check: “did the recalculation produce the same result as the previous version of the algorithm?”.

fun main() {
    val oldCalc = intArrayOf(120, 0, 50, 80, 0, 0, 10)
    val newCalc = intArrayOf(120, 0, 50, 80, 0, 0, 10)

    val same = oldCalc.contentEquals(newCalc)
    println("Did the weekly totals match? $same") // Did the weekly totals match? true
}

This is a simple but very real “sanity test”: if you refactor code and are afraid of breaking logic, comparing arrays by content gives you a quick signal.

3. contentDeepEquals() for nested arrays

As soon as an array contains other arrays, the usual contentEquals() becomes insufficient. It will compare the top level, but nested elements will be compared as separate container objects. And the same problem pops up again: “containers are different, even though the inside is the same.”

That is exactly why Kotlin provides contentDeepEquals().

Example: a “two-dimensional table” of expenses

Imagine we want to store expenses as “week × categories” as a table: 7 rows (days), and in each row, for example, 3 numbers (food, transport, other). This can be represented as a nested array.

fun main() {
    val a = arrayOf(
        intArrayOf(100, 20, 0),
        intArrayOf(0, 0, 10)
    )
    val b = arrayOf(
        intArrayOf(100, 20, 0),
        intArrayOf(0, 0, 10)
    )

    println(a.contentEquals(b))     // false
    println(a.contentDeepEquals(b)) // true
}

Why does contentEquals return false? Because it sees the elements of the outer array—and those elements are IntArray, i.e., separate arrays. They are different by reference. So contentEquals at the “top” says: “the first element is not equal to the first element,” and that is it.

But contentDeepEquals “goes inside” and compares the contents of nested arrays recursively, so we get true.

A small diagram: why deep is needed

flowchart TD
    A[Top-level Array] --> B1[Element 0: IntArray]
    A --> B2[Element 1: IntArray]

    C[Another top-level Array] --> D1[Element 0: IntArray]
    C --> D2[Element 1: IntArray]

    B1 -. contentEquals compares as an object .- D1
    B2 -. contentEquals compares as an object .- D2

    B1 --> E1[100, 20, 0]
    D1 --> F1[100, 20, 0]

Idea: contentEquals at the top level does not “unroll” nested arrays by default, so you need contentDeepEquals, which does it intentionally.

4. Snapshots and aliasing: the “before/after” trap

Even if you use contentEquals, you can hit another unpleasant issue: you compare an array “before” and “after,” but in reality you do not have two arrays—you have the same array under two names.

This is the same story we discussed for MutableList: assigning a reference value creates an alias (a second name). This applies to arrays too.

Example: two names, one array

fun main() {
    val week = intArrayOf(10, 20, 30)
    val alias = week

    alias[0] = 999

    println(week.joinToString())  // 999, 20, 30
    println(week === alias)       // true
}

Here, comparing “before/after” is pointless because you no longer have the “before.”

Solution: make a copy if you need a snapshot

If you want to preserve the old state of an array, make a copy (for example, copyOf()—you have already seen it in the topic of arrays and fixed size).

fun main() {
    val week = intArrayOf(10, 20, 30)
    val snapshot = week.copyOf()

    week[0] = 999

    println(snapshot.joinToString())          // 10, 20, 30
    println(snapshot.contentEquals(week))     // false
}

And now this is a real “before/after”: one array preserved the past state, the other changed.

In the context of our app, this is genuinely useful: for example, you recalculate weekly totals and want to compare whether the result changed. A snapshot helps you honestly see what happened.

5. Mini utilities for the project

In a learning project, we try to write code so that main() does not turn into a tangled carpet of wires. So it is useful to wrap array comparisons into small functions. This also makes the code more readable: instead of “what is this contentDeepEquals doing here?” you will have “compare weekly matrices.”

Function for a flat array

fun sameWeeklyTotals(a: IntArray, b: IntArray): Boolean {
    return a.contentEquals(b)
}

fun main() {
    val x = intArrayOf(1, 2, 3)
    val y = intArrayOf(1, 2, 3)

    println(sameWeeklyTotals(x, y)) // true
}

A super-simple function, but it wins in “words”: you immediately read the intent.

Function for a “table”

fun sameWeekMatrix(a: Array<IntArray>, b: Array<IntArray>): Boolean {
    return a.contentDeepEquals(b)
}

fun main() {
    val a = arrayOf(intArrayOf(1, 2), intArrayOf(3, 4))
    val b = arrayOf(intArrayOf(1, 2), intArrayOf(3, 4))

    println(sameWeekMatrix(a, b)) // true
}

Notice how nicely it reads: sameWeekMatrix immediately hints that the structure is nested and the comparison will be “deep.”

6. Diagnostics: how to print arrays

When you compare arrays, the next thought is often: “OK, they are not equal. But where exactly do they differ?” And this is where printing an array becomes part of debugging.

For flat arrays you can use joinToString(), and for nested ones—“deep” representations like contentDeepToString().

Flat array

fun main() {
    val a = intArrayOf(1, 2, 3)
    val b = intArrayOf(1, 999, 3)

    println("a = ${a.joinToString()}") // a = 1, 2, 3
    println("b = ${b.joinToString()}") // b = 1, 999, 3
}

Nested array

fun main() {
    val a = arrayOf(intArrayOf(1, 2), intArrayOf(3, 4))
    val b = arrayOf(intArrayOf(1, 2), intArrayOf(3, 999))

    println(a.contentDeepToString()) // [[1, 2], [3, 4]]
    println(b.contentDeepToString()) // [[1, 2], [3, 999]]
}

These printouts are especially useful when you build reports/tables and then compare results after sorts or recalculations.

7. Typical mistakes when comparing arrays

Mistake #1: using == “out of habit” and trusting the result.
Lists (List) often really are compared “by content” via ==, so your hand automatically writes the same for arrays. But arrays are an exception: Kotlin explicitly warns not to use ==/!= to compare array elements. If you want to compare elements, your default choice is contentEquals().

Mistake #2: using contentEquals for nested arrays and being surprised by false.
When an array contains arrays, contentEquals compares top-level elements as separate objects. As a result, two “data-wise identical” 2D arrays look different. In such structures you need contentDeepEquals(), which goes inside and compares the nested contents.

Mistake #3: comparing “before/after” without saving the “before.”
Sometimes you think you have two arrays, but in reality you have one and the same structure under two names. Then any change “after” instantly changes “before” as well, and the comparison turns into theater of the absurd. If you need a snapshot, make a copy (for example, copyOf()), and only then compare.

Mistake #4: confusing the task “is it the same container?” with the task “is it the same data?”
=== can be useful, but it is not a replacement for contentEquals. === answers the question “is this the same object?” (for example, you accidentally passed an array somewhere and want to check whether it is the same instance). But “the data matches” is contentEquals/contentDeepEquals.

Mistake #5: checking only the fact of false, but not being able to quickly see the difference.
When the comparison fails, the next step is printing. For flat arrays, joinToString() works well; for nested ones, contentDeepToString(). This speeds up debugging dramatically, because you stop guessing “where exactly did it not match?” and start seeing concrete numbers/strings.

1
Task
Kotlin SELF, level 23, lesson 4
Locked
Three array checks
Three array checks
1
Task
Kotlin SELF, level 23, lesson 4
Locked
Weekly summary
Weekly summary
1
Task
Kotlin SELF, level 23, lesson 4
Locked
Two tables: comparison
Two tables: comparison
1
Survey/quiz
Sorting, level 23, lesson 4
Unavailable
Sorting
Sorting
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION