How do I compare two arrays in scala?
From Programming Scala:
Array(1,2,4,5).sameElements(Array(1,2,4,5))
You need to change your last line to
a.deep == b.deep
to do a deep comparison of the arrays.
a.corresponds(b){_ == _}
Scaladoc:
true
if both sequences have the same length andp(x, y)
istrue
for all corresponding elementsx
ofthis
wrapped array andy
ofthat
, otherwisefalse
For best performance you should use:
java.util.Arrays.equals(a, b)
This is very fast and does not require extra object allocation. Array[T]
in scala is the same as Object[]
in java. Same story for primitive values like Int
which is java int
.
As of Scala 2.13, the deep
equality approach doesn't work and errors out:
val a: Array[Int] = Array(1,2,4,5)
val b: Array[Int] = Array(1,2,4,5)
a.deep == b.deep // error: value deep is not a member of Array[Int]
sameElements
still works in Scala 2.13:
a sameElements b // true