How do I compare two arrays in scala?

后端 未结 5 1441
情书的邮戳
情书的邮戳 2020-12-13 01:43
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 sequen

相关标签:
5条回答
  • 2020-12-13 01:56

    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.

    0 讨论(0)
  • 2020-12-13 01:57

    You need to change your last line to

    a.deep == b.deep
    

    to do a deep comparison of the arrays.

    0 讨论(0)
  • 2020-12-13 02:00
      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

    0 讨论(0)
  • 2020-12-13 02:12

    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
    
    0 讨论(0)
  • 2020-12-13 02:16

    From Programming Scala:

    Array(1,2,4,5).sameElements(Array(1,2,4,5))
    
    0 讨论(0)
提交回复
热议问题