如何比较scala中的两个数组?

时间:2021-07-14 04:06:28
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?

是否有模式匹配的方法来检查两个数组(或序列)是否相等?

4 个解决方案

#1


82  

You need to change your last line to

你需要把最后一行改为

a.deep == b.deep

to do a deep comparison of the arrays.

对数组进行深入的比较。

#2


75  

From Programming Scala:

从Scala编程:

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

#3


18  

  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

如果两个序列的长度相同,且p(x, y)对这个封装数组的所有对应元素x和y都为真,则为假

#4


2  

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.

这非常快,不需要额外的对象分配。scala中的数组[T]与java中的对象[]相同。对于像Int (java Int)这样的原始值,情况也是如此。

#1


82  

You need to change your last line to

你需要把最后一行改为

a.deep == b.deep

to do a deep comparison of the arrays.

对数组进行深入的比较。

#2


75  

From Programming Scala:

从Scala编程:

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

#3


18  

  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

如果两个序列的长度相同,且p(x, y)对这个封装数组的所有对应元素x和y都为真,则为假

#4


2  

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.

这非常快,不需要额外的对象分配。scala中的数组[T]与java中的对象[]相同。对于像Int (java Int)这样的原始值,情况也是如此。