scala 如何比较scala中的两个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5393243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I compare two arrays in scala?
提问by Phil H
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?
是否有模式匹配的方法来查看两个数组(或序列)是否等效?
回答by Moritz
You need to change your last line to
您需要将最后一行更改为
a.deep == b.deep
to do a deep comparison of the arrays.
对数组进行深入比较。
回答by sc_ray
回答by The Archetypal Paul
a.corresponds(b){_ == _}
Scaladoc:
trueif both sequences have the same length andp(x, y)istruefor all corresponding elementsxofthiswrapped array andyofthat, otherwisefalse
Scaladoc:
true如果两个序列具有相同的长度和p(x, y)是true对于所有对应的元件x的this包裹阵列和y的that,否则false
回答by jjuraszek
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 Intwhich is java int.
这非常快并且不需要额外的对象分配。Array[T]在 scala 中与Object[]在 java 中相同。原始值的相同故事,例如Intwhich 是 java int。
回答by Powers
As of Scala 2.13, the deepequality approach doesn't work and errors out:
从 Scala 2.13 开始,deep等式方法不起作用并出现错误:
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]
sameElementsstill works in Scala 2.13:
sameElements仍然适用于 Scala 2.13:
a sameElements b // true

