How do I compare two arrays in scala?

筅森魡賤 提交于 2019-12-17 17:35:14

问题


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?


回答1:


You need to change your last line to

a.deep == b.deep

to do a deep comparison of the arrays.




回答2:


From Programming Scala:

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



回答3:


  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




回答4:


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.



来源:https://stackoverflow.com/questions/5393243/how-do-i-compare-two-arrays-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!