Search code examples
arraysarraylistkotlincomparisonequality

How to check value exist inside 2D array with Kotlin?


I'm trying to find if an array exists inside a 2D array using contains(...) but even though it is in the array the return value is false. Why and how can I make it work?

val obs = arrayOf (arrayOf(5, 5),arrayOf(4, 2),arrayOf(2, 3))
println(obs.contains(arrayOf(2, 3))) // false

val obs1 = arrayListOf (arrayListOf(5, 5), arrayListOf(4, 2), arrayListOf(2, 3))
println(obs1.contains(arrayListOf(2, 3))) // true

Solution

  • obs.contains(arrayOf(2,3)) will only yield true if the reference of arrayOf(2,3) is equal to any of the references in obs. in other words, it's resorting to reference equality for arrays instead of content equality.

    You can get the result you require by using contentEquals:

    println(obs.any { it.contentEquals(arrayOf(2,3)) }) // true
    

    The second version prints as expected because collections are compared structurally.


    You may find What you didn’t know about arrays in Kotlin of interest.