val a: Array[Int] = Array(1,2,4,5)
val b: Array[Int] = Array(1,2,4,5)
a==b // false
Is there a pattern-matching way to see if two arrays (or sequences) are equivalent?
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.
deep
. It creates a collection, that forwards all calls of the apply
method to the original array.
Array.equals
? That doesn't seem to provide a deep comparison.
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
.
val t0 = System.nanoTime(); val r = (java.util.Arrays.equals(a,b)) ; val t1 = System.nanoTime(); t1 - t0
on this sample code and very similar code for the other examples ... This option was way faster than the other examples.
Mar 21, 2018 at 20:08
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
It didn't look like most of the provided examples work with multidimensional arrays. For example
val expected = Array(Array(3,-1,0,1),Array(2,2,1,-1),Array(1,-1,2,-1),Array(0,-1,3,4))
val other = Array(Array(3,-1,0,1),Array(2,2,1,-1),Array(1,-1,2,-1),Array(0,-1,3,4))
assert(other.sameElements(expected))
returns false, throws an assertion failure
deep doesn't seem to be a function defined on Array.
For convenience I imported scalatest matchers and it worked.
import org.scalatest.matchers.should.Matchers._
other should equal(expected)
sameElements
sameElements
doesn't do the trick for nested arrays, because it's not recursive. Moritz' answer below is the appropriate one now (which should probably be added to the older answers).