开发者

How do I compare two arrays in scala?

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.


  a.corresponds(b){_ == _}

Scaladoc: true if both sequences have the same length and p(x, y) is true for all corresponding elements x of this wrapped array and y of that, otherwise false


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


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)  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜