2

I have a 2d array and I want to check whether an array exists inside the 2d array.

I have tried:

var arr = Array(Array(2,1), Array(4,3))
var contain = arr.contains(Array(4, 3))
println(contain)

This should print true but it doesn't work.

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
  • 1
    The problem is that `Arrays` use **reference equality** instead of **value equality**. The best would be to do not use `Arrays`. Or you can create your own method that iterates over the matrix, to check if the value exists. – Luis Miguel Mejía Suárez Sep 03 '19 at 13:12

3 Answers3

4

Method contains doesn't work because it uses equals to determine equality and for arrays equals is using reference equality, so it will return true only for two references pointing the same object.

You could use find + sameElements:

var arr = Array(Array(2,1), Array(4,3))
var contain = arr.find(_.sameElements(Array(4, 3))).isDefined
println(contain)
Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
2

Consider using ArrayBuffer instead of Array, if you need mutable collection, like so

val arr = ArrayBuffer(ArrayBuffer(2,1), ArrayBuffer(4,3))
val contain = arr.contains(ArrayBuffer(4, 3))
println(contain) 

which outputs

true

Also consider question What is the difference between ArrayBuffer and Array

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

A more elegant solution would be the following

val array = Array(Array(2,1), Array(4,3))
val result = array.exists(_.sameElements(Array(4, 3)))
println(result)

Output

true
JavaTechnical
  • 8,846
  • 8
  • 61
  • 97