-1

In scala, how can I check if a multidimensional array of Int contains an array, for instance:

val test = Array(Array(1, 2), Array(2, 1))

test.contains(Array(1, 2)) // this results to false

test.contains(test(0)) // this results to true

So it seems scala is comparing the object reference too, in the first case, despite having the same elements, it is a different object, hence returning false. Is this right?

In the second case, I'm testing against one of the same objects already contained in the list, hence returning true.

How can I achieve the expected result, i.e., checking if a multidimensional array in Scala contains a specific array?

I have seen this is possible with tuples, but not with arrays.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
Ohtar10
  • 128
  • 1
  • 11
  • I think It helps for you to understand why it can't. https://nrinaudo.github.io/scala-best-practices/unsafe/array_comparison.html – Kideok Kim Apr 03 '20 at 00:08

2 Answers2

3

Unless you require raw performance, identified by proper measurements with say jmh, or require Java interop, then try to avoid Array and instead use Scala collections proper such as List:

List(List(1,2), List(2,1)).contains(List(1,2))  // res2: Boolean = true

If you must use Array, then try combination of exists and sameElements like so

test.exists(_.sameElements(Array(1,2)))         // res1: Boolean = true

Why doesn't Array's == function return true for Array(1,2) == Array(1,2)?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
3

You can use sameElements:

test.exists(_.sameElements(Array(1, 2)))
Andronicus
  • 25,419
  • 17
  • 47
  • 88