views:

167

answers:

1
scala> List(1,2,3) == List(1,2,3)

res2: Boolean = true

scala> Map(1 -> "Olle") == Map(1 -> "Olle")

res3: Boolean = true

But when trying to do the same with Array, it does not work the same. Why?

scala> Array('a','b') == Array('a','b')

res4: Boolean = false

I have used 2.8.0.RC7 and 2.8.0.Beta1-prerelease.

+9  A: 

Because the definition of "equals" for Arrays is that they refer to the same array.

This is consistent with Java's array equality, using Object.Equals, so it compares references.

If you want to check pairwise elements, then use sameElements

Array('a','b').sameElements(Array('a','b'))

or deepEquals, which has been deprecated in 2.8, so instead use:

Array('a','b').deep.equals(Array('a','b').deep)

There's a good Nabble discussion on array equality.

Stephen
Is Array the only exception to the general rule of comparing the actual elements for the built in collections? All other collections I have tried compare the elements.
olle kullberg
@olle - as far as I know, it is the only collection that exhibits this behavior. Even `ArrayList` compares elements. What I can't figure out, is how this is supposed to be learned from the documentation :)
Stephen
also see http://stackoverflow.com/questions/2481149/why-does-array0-1-2-array0-1-2-not-return-the-expected-result
oluies
@Brent : Excellent link, thanks.
Stephen
@olle : The java array _is_ an object ( http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html , especially section 10.8) `WrappedArray` wraps the java array in a class. `Array` _is_ the java array. The reason it can't override `Object.equals` (and provide a specialized equals) is because it does not subclass the java array. If it wrapped array, or subclassed it, it would behave as you expected. Gotta say, my answer is entirely accurate, except for not going into detail about _why_ it can't override the behavior.
Stephen
@olle : BTW, Your explanation is factually incorrect when you say "the correct explanation ..." If you don't accept it, fine, but the -1 is adding insult to injury! :)
Stephen
My bad, you are correct! I've read in "Beyond Java" (B. Tate) that the Java array is not an object, but just as you said, this is not true.
olle kullberg
@olle : Thanks for clearing that up. And I'll be staying away from that book :)
Stephen
Scala SID #7 is a good read also http://www.scala-lang.org/sid/7
oluies