How do I compare two arrays in scala?

ArraysScalaPattern Matching

Arrays Problem Overview


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?

Arrays Solutions


Solution 1 - Arrays

From Programming Scala:

Array(1,2,4,5).sameElements(Array(1,2,4,5))

Solution 2 - Arrays

You need to change your last line to

a.deep == b.deep

to do a deep comparison of the arrays.

Solution 3 - 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

Solution 4 - Arrays

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.

Solution 5 - Arrays

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

Solution 6 - Arrays

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)  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhil HView Question on Stackoverflow
Solution 1 - Arrayssc_rayView Answer on Stackoverflow
Solution 2 - ArraysMoritzView Answer on Stackoverflow
Solution 3 - ArraysThe Archetypal PaulView Answer on Stackoverflow
Solution 4 - ArraysjjuraszekView Answer on Stackoverflow
Solution 5 - ArraysPowersView Answer on Stackoverflow
Solution 6 - ArraysdiscordView Answer on Stackoverflow