为什么`阵列(0,1,2)==阵列(0,1,2)`不会返回预期的结果? [英] Why does `Array(0,1,2) == Array(0,1,2)` not return the expected result?
问题描述
据我了解,Scala的==定义了两个对象的自然平等的。
As far as I understand, Scala's == defines the natural equality of two objects.
我预计,阵列(0,1,2)==阵列(0,1,2)
比较自然的平等。例如,检查是否当与其它阵列的对应元件相比,该数组中的所有元素返回true。
I expected that Array(0,1,2) == Array(0,1,2)
compares the natural equality. For example, checks if all elements of the array return true when compared with the corresponding elements of the other array.
人告诉我,Scala的阵列
只是一个Java []
只比较认同。那岂不是更有意义的覆盖的
等于
方法比较自然的平等呢?
People told me that Scala's Array
is just a Java []
which only compares identity. Wouldn't it be more meaningful to override Array
'sequals
method to compare natural equality instead?
推荐答案
斯卡拉2.7试图将功能添加到Java []
阵列,跑到角落案件是有问题。斯卡拉2.8已经宣布,数组[T]
是 T []
,但它提供的包装和等价物。
Scala 2.7 tried to add functionality to Java []
arrays, and ran into corner cases that were problematic. Scala 2.8 has declared that Array[T]
is T[]
, but it provides wrappers and equivalents.
请尝试以下2.8(编辑/注:为RC3的, GenericArray
是 ArraySeq
- 感谢返璞词指出这一点):
Try the following in 2.8 (edit/note: as of RC3, GenericArray
is ArraySeq
--thanks to retronym for pointing this out):
import scala.collection.mutable.{GenericArray=>GArray, WrappedArray=>WArray}
scala> GArray(0,1,2) == GArray(0,1,2)
res0: Boolean = true
scala> (Array(0,1,2):WArray[Int]) == (Array(0,1,2):WArray[Int])
res1: Boolean = true
GenericArray
行为就像阵列
,但在添加了所有的Scala集合东西。 WrappedArray
包装的Java []
阵列;以上,我投一个普通数组,然后比较了包裹阵列(不是调用隐式转换功能更容易)。这些包装,虽然背靠一个 []
阵列,也给你所有的收集东西。
GenericArray
acts just like Array
, except with all the Scala collections goodies added in. WrappedArray
wraps Java []
array; above, I've cast a plain array to it (easier than calling the implicit conversion function) and then compared the wrapped arrays. These wrappers, though backed by a []
array, also give you all the collection goodies.
这篇关于为什么`阵列(0,1,2)==阵列(0,1,2)`不会返回预期的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!